Post

Move Zeroes

LeetCode https://leetcode.cn/problems/move-zeroes/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int slow = 0;
        int fast = 0;
        while (fast < nums.length) {
            if (nums[fast] != 0) {
                nums[slow++] = nums[fast++];
            } else {
                fast++;
            }
        }
        while (slow < nums.length) {
            nums[slow++] = 0;
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
    // slow: slow 的左侧都是非0,不包括 slow 位置的。
    // fast: fast 的右侧是还没确定的区域。
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int slow = 0;
        int fast = 0;
        for (; fast < nums.length; fast++) {
            if (nums[fast] != 0) {
                exchange(nums, slow, fast);
                slow++;
            } 
        }
    }

    private void exchange(int[] nums, int i, int j) {
        if (i >= j) {
            return;
        }
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

Complexity

  • Time = O(n)
  • Space = O(1)
This post is licensed under CC BY 4.0 by the author.