283. Move Zeroes - easy

自己的解法,用了两个pointer。速度比较慢。
答案很简单,用了一个pointer记录非零数insert的position, 并且用iteration做循环。

My code, 1st:

public class Solution {
    public void moveZeroes(int[] nums) {
        /** two pointers:
         * 1st first zero, 2nd curr scan iterm
         */
        int zero = -1, curr = 0;
        for (int i=0; i

看了答案之后:
这种做法问题是改变了array本身。

public class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0)   return;
        
        int curr = 0;
        for (int num : nums)
            if (num != 0)   nums[curr++] = num;
        
        while (curr < nums.length)
            nums[curr++] = 0;
    }
}

想法:在scan的时候没有遇见0,就只向后移动。
does not matter, just 1ms.
时间: O(n);
空间:O(n);


Never stop. Oct 19 2016

你可能感兴趣的:(283. Move Zeroes - easy)