283. (Move Zeroes)移动零

该博客介绍了LeetCode第283题——移动零的解题思路和代码实现。通过使用双指针方法,可以在原数组上就地操作,将所有0移动到数组末尾,同时保持非零元素的相对顺序。博主提供了Python、Java和C++三种语言的代码示例,并分析了时间复杂度和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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 <= 10410^4104
-2312^{31}231 <= nums[i] <= 2312^{31}231 - 1

提示:

1 <= nums.length <= 10410^4104
-2312^{31}231 <= nums[i] <= 2312^{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),只需常数的空间存放若干变量。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值