LeetCode 题解工作台
移动零
给定一个数组 nums ,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 请注意 ,必须在不复制数组的情况下原地对数组进行操作。 示例 1: 输入: nums = [0,1,0,3,12] 输出: [1,3,12,0,0] 示例 2: 输入: nums = [0] 输出: […
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们用一个指针 记录当前待插入的位置,初始时 $k = 0$。 然后我们遍历数组 ,每次遇到一个非零数,就将其与 交换,同时将 的值加 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个数组 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
进阶:你能尽量减少完成的操作次数吗?
解题思路
方法一:双指针
我们用一个指针 记录当前待插入的位置,初始时 。
然后我们遍历数组 ,每次遇到一个非零数,就将其与 交换,同时将 的值加 。
这样我们就可以保证 的前 个元素都是非零的,且它们的相对顺序与原数组一致。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.