lintcode539 - Move Zeroes

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
Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Notice
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.

转换思路,swap的时候不是想着把零都移到最后面去(这种思路会让非零数相对位置变乱),而是把非零数挪到前面连续非零数的尾端。
两根指针,一根指着下一个可以插入的位置(非零数的下一个),一根指着需要被swap的非零数对象。
前面这根指针每swap一下++,因为前端多了一个新非零数嘛。
后面这根指针向前一个个滑动,每次滑动到找到非零数了停下来进行swap。

因为要保持非零数的相对位置,所以想到不能用相向双指针,而应该是同向双指针。

我的实现

public class Solution {
    /**
     * @param nums: an integer array
     * @return: nothing
     */
    public void moveZeroes(int[] nums) {
        // write your code here
        int zero = 0;
        int nonzero = 0;
        while (zero < nums.length && nums[zero] != 0) {
            zero++;
            nonzero++;
        }
        while (nonzero < nums.length && nums[nonzero] == 0) {
            nonzero++;
        }
        while (zero < nums.length && nonzero < nums.length) {
            int temp = nums[zero];
            nums[zero] = nums[nonzero];
            nums[nonzero] = temp;
            zero++;
            while (nonzero < nums.length && nums[nonzero] == 0) {
                nonzero++;
            }
        }
    }
}

九章实现

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

猜你喜欢

转载自www.cnblogs.com/jasminemzy/p/9479214.html
今日推荐