【双指针】283. 移动零

题目
两种方法时间复杂度相同都是O(n),方法2操作更少一些

1.解法1: 有优化空间

class Solution {
    public void moveZeroes(int[] nums) {
        int slow = 0, fast = 0;
        while (fast < nums.length) {
            if (nums[fast] != 0) {
                if (slow == fast) {
                    ++slow;
                    ++fast;
                } else {
                    nums[slow++] = nums[fast++];
                }
            } else {
                ++fast;
            }
        }
        while (slow < nums.length) {
            nums[slow++] = 0;
        }
    }
}

解法2:最佳写法

class Solution {
    public void moveZeroes(int[] nums) {
        int slow = 0, fast = 0;
        while (fast < nums.length) {
            if (nums[fast] != 0) {
                if (nums[slow] != 0) {
                    ++slow;
                    ++fast;
                } else {
                    nums[slow++] = nums[fast];
                    nums[fast++] = 0;
                }
            } else {
                ++fast;
            }
        }
    }
}

你可能感兴趣的:(力扣Top100,双指针)