Monday, September 19, 2016

[LintCode] 539 Move Zeroes 解题报告

Description
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.


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


Example
Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].


思路
用两个指针遍历数组。
一个指针指向可以swap的位置,另一个去找不是0的数。
碰到不是0的,就swap。




Code
public class Solution {
    /**
     * @param nums an integer array
     * @return nothing, do this in-place
     */
    public void moveZeroes(int[] nums) {
        // Write your code here
        int i = 0;
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != 0) {
                swap(nums, i, j);
                i++;
            }
        }
    }
    
    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}