283. Move Zeroes

QUESTION:

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note:

You must do this in-place without making a copy of the array. Minimize the total number of operations.

EXPLANATION:

这道题其实之前就已经做过,但是这次是要做一个不依赖其他方式,只使用O(n)的时间复杂度。
其实需要明确的是:如果当前位置是0,那么后面的数只有两种情况,1,是0,2,不是0
1.是0,那么就继续往前,直到不是0,进行切换, 那么下一个还是index+1
2.不是0,那么就进行切换,下一个还是index+1
总结出来,只要进行了切换,那么index就需要进行+1

SOLUTION:

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