且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode]--283. Move Zeroes

更新时间:2021-11-17 19:12:50

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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

我想着先不是零的都移到前面,然后后面的补零。

public void moveZeroes(int[] nums) {
        int j = 0;
        for (int i = 0; i < nums.length; i++)
            if (nums[i] != 0)
                nums[j++] = nums[i];
        while (j < nums.length)
            nums[j++] = 0;
    }

另外一种,边移边补零。

public void moveZeroes(int[] nums) {
        int i = 0;
        int j = 0;
        while (j < nums.length) {
            if (nums[j] != 0) {
                if (j != i) {
                    nums[i++] = nums[j];
                    nums[j] = 0;
                } else
                    ++i;
            }
            ++j;
        }
    }