283. Move Zeroes - jiejackyzhang/leetcode-note GitHub Wiki
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.
 
##Approach 1 这道题目的关键是如何使操作次数最小化。
这里可以采用双指针的思路,lastNonZeroFoundAt和current。 lastNonZeroFoundAt是非零元素应该处于的位置。 注意到:
- All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.
 - All elements between the current and slow pointer are zeroes.
 
因此每当我们碰到一个非零元素,只需将这两个指针指着的元素交换,然后两个指针都前进; 若碰到的是零,则只让current指针前进。
这样,总的操作数即为非零元素的个数。
public class Solution {
    private void swap(int[] nums, int i, int j) {
        if(i == j) return;
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
    public void moveZeroes(int[] nums) {
        for(int lastNonZeroFoundAt = 0, cur = 0; cur < nums.length; cur++) {
            if(nums[cur] != 0) {
                swap(nums, lastNonZeroFoundAt, cur);
                lastNonZeroFoundAt++;
            }
        }
    }
}
##Approach 2 可以用"26. Remove Duplicates from Sorted Array"相似的方法。 把不是零的数字依次赋值,最后剩下的都赋值为0。
public class Solution {
    public void moveZeroes(int[] nums) {
        int k = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] != 0) nums[k++] = nums[i];
        }
        while(k < nums.length) nums[k++] = 0;
    }
}