leetcode- Move Zeros

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:

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

注意点:这里和单纯的把0扔到后边不一样,非0数的整体顺序是不变的!!!

代码:

package leetcode;

public class MoveZeros {

    /*public void moveZeroes(int[] nums) {                   
        int len = nums.length;
        if (len == 1)
            return;
        int p1 = 0;
        int p2 = len - 1;
        while (p1 <= p2) {
            if (nums[p1] == 0) {
                if (nums[p2] == 0) {
                    p2--;
                } else {
                    nums[p1] = nums[p2];
                    nums[p2] = 0;
                    p2--;
                }
            } else {
                p1++;
            }
        }

    }*/
    public void moveZeroes(int[] nums){             //思路:设置两个指针
        int len = nums.length;
        if(len == 1 ) return ;
        int p1 = 0;
        int p2 = 0;
        while(p2 < len){
            if(nums[p2] != 0){
                int tmp = nums[p1];
                nums[p1] = nums[p2];             //这里不能直接赋0;
                nums[p2] = tmp;
                p1++;
                p2++;
            }else{
                p2++;
            }
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

posted @ 2016-04-15 13:33  wangb021  阅读(113)  评论(0编辑  收藏  举报