Cindy's Blog

アマゾンで働いているエンジニアの日常

LeetCode 283. Move Zeroes

Follow up: Could you minimize the total number of operations done?

https://leetcode.com/problems/move-zeroes/

    //firstZeroIndex -> z
// z: -1
    // i
    //[1,3,12,0,0]
    //when nums[i] = 0
       //if z = -1, then z = i
    //else
       //if z != -1 (had zero in front)
       // swap
      // z += 1;
    //from z ~ i as t, nums[t] = 0 is promised
    

class Solution {
    public void moveZeroes(int[] nums) {
        int firstZeroIndex = -1;
        for (int i = 0; i < nums.length; i++){
            if (nums[i] == 0){
                if (firstZeroIndex == -1){
                    firstZeroIndex = i;
                }
            } else {
                if (firstZeroIndex != -1){
                    int temp = nums[firstZeroIndex];
                    nums[firstZeroIndex] = nums[i];
                    nums[i] = temp;
                    
                    firstZeroIndex += 1;
                }
            }
        }
    }
}