283. (Move Zeroes)移动零

Posted OIqng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了283. (Move Zeroes)移动零相关的知识,希望对你有一定的参考价值。

题目:

Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

给定一个整数数组nums,在保持非零元素的相对顺序的同时,将所有0移动到数组的末尾。

注意,必须在不复制数组的情况下就地执行此操作。

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

示例1:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

Example 2:

Input: nums = [0]
Output: [0]

示例2:

输入: [0]
输出: [0]

Constraints:

1 <= nums.length <= 1 0 4 10^4 104
- 2 31 2^{31} 231 <= nums[i] <= 2 31 2^{31} 231 - 1

提示:

1 <= nums.length <= 1 0 4 10^4 104
- 2 31 2^{31} 231 <= nums[i] <= 2 31 2^{31} 231 - 1

Follow up:

Could you minimize the total number of operations done?

进阶:

你能把操作的总数最小化吗?

解题思路:

方法:双指针

根据题目要求我们只能在原数组上进行操作,我们使用双指针交换数组元素。定义Left指向元素0,定义right指向非0元素,当nums[right]>0是交换nums[left]、nums[right]、left++、right++否则right++。

Python代码

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        n = len(nums)
        left = right = 0
        while right < n:
            if nums[right] != 0:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1
            right += 1

Java代码

class Solution {
    public void moveZeroes(int[] nums) {
        int n = nums.length, left = 0, right = 0;
        while (right < n) {
            if (nums[right] != 0) {
                swap(nums, left, right);
                left++;
            }
            right++;
        }
    }

    public void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}

C++代码

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size(), left = 0, right = 0;
        while (right < n) {
            if (nums[right]) {
                swap(nums[left], nums[right]);
                left++;
            }
            right++;
        }
    }
};

复杂度分析

时间复杂度:O(n),其中 n 为序列长度。

空间复杂度:O(1),只需常数的空间存放若干变量。

以上是关于283. (Move Zeroes)移动零的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 283. Move Zeroes 移动零

LeetCode 283. Move Zeroes (移动零)

LeetCode 283. 移动零 Move Zeroes (Easy)

LeetCode 283 Move Zeroes(移动全部的零元素)

LeetCode 283. Move Zeroes

LeetCode 283 Move Zeroes