LeetCode 题解工作台

移动零

给定一个数组 nums ,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 请注意 ,必须在不复制数组的情况下原地对数组进行操作。 示例 1: 输入: nums = [0,1,0,3,12] 输出: [1,3,12,0,0] 示例 2: 输入: nums = [0] 输出: […

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们用一个指针 记录当前待插入的位置,初始时 $k = 0$。 然后我们遍历数组 ,每次遇到一个非零数,就将其与 交换,同时将 的值加 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

 

示例 1:

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

示例 2:

输入: nums = [0]
输出: [0]

 

提示:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

 

进阶:你能尽量减少完成的操作次数吗?

lightbulb

解题思路

方法一:双指针

我们用一个指针 kk 记录当前待插入的位置,初始时 k=0k = 0

然后我们遍历数组 nums\textit{nums},每次遇到一个非零数,就将其与 nums[k]\textit{nums}[k] 交换,同时将 kk 的值加 11

这样我们就可以保证 nums\textit{nums} 的前 kk 个元素都是非零的,且它们的相对顺序与原数组一致。

时间复杂度 O(n)O(n),其中 nn 是数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        k = 0
        for i, x in enumerate(nums):
            if x:
                nums[k], nums[i] = nums[i], nums[k]
                k += 1
speed

复杂度分析

指标
时间complexity is O(n) since each element is visited at most once. Space complexity is O(1) because the rearrangement occurs in-place without additional arrays.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Watch for attempts to create a copy of the array instead of in-place rearrangement.

  • question_mark

    Check if candidates maintain the relative order of non-zero elements while moving zeros.

  • question_mark

    Look for correct use of a two-pointer invariant to minimize unnecessary swaps.

warning

常见陷阱

外企场景
  • error

    Swapping elements unnecessarily even when non-zero is already in place.

  • error

    Failing to handle arrays where all elements are zeros or all non-zeros.

  • error

    Using extra memory instead of modifying the input array directly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Move all occurrences of a specific number to the end while preserving order.

  • arrow_right_alt

    Partition an array into even and odd numbers using a similar two-pointer approach.

  • arrow_right_alt

    Move zeros to the beginning instead of the end while keeping non-zero order.

help

常见问题

外企场景

移动零题解:双·指针·invariant | LeetCode #283 简单