[leetcode] 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.

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.

分析:两个指针p1, p2;其中p1指向元素0,p2指向p1后面的非0元素,然后两两交换即可,注意边界条件。

Java代码:

    public void moveZeroes(int[] nums) { 
        if (nums.length == 0) {
            return;
        }
        int i = 0, j = 0;
        while (j < nums.length) {
            while (i < nums.length && nums[i] != 0) {
                i++;
            }
            j = i + 1;
            while (j < nums.length && nums[j] == 0) {
                j++;
            }
            if (j < nums.length) {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
            }
        }
    }
原文地址:https://www.cnblogs.com/lasclocker/p/4938275.html