NeetCode #183LC-283EasyTwo Pointers
← Back to All Problems#183 · #283 · Move Zeroes(移动零)
📌 Problem Statement & Constraints
Given an integer array
nums, move all 0s to the end while maintaining the relative order of the non-zero elements, in place. Constraints: 1 <= nums.length <= 10^4, -2^31 <= nums[i] <= 2^31 - 1.💡 Core Algorithmic Approaches
- Use a write pointer
kfor the next non-zero slot. Scan with a read pointer and copy every non-zero value tonums[k]. - After the scan, fill the remaining slots from
kto the end with zeros. - This preserves the relative order of the non-zero elements, which a swap-based approach with a two-ended pointer would not.
- An alternative is to swap the non-zero value into position
kimmediately, which achieves the same result in one pass.
💻 Benchmark Python3 Implementation
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
k = 0 # next slot for a non-zero value
for i in range(len(nums)):
if nums[i] != 0:
nums[k] = nums[i]
k += 1
for i in range(k, len(nums)):
nums[i] = 0 # pad the tail with zeros
# One-pass swap variant (also preserves order)
class Solution2:
def moveZeroes(self, nums: List[int]) -> None:
k = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[k], nums[i] = nums[i], nums[k]
k += 1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one or two passes.
💾 Space Complexity
O(1): in place.
⚠️ Interview Pitfalls & Follow-ups
- Using
nums.remove(0)in a loop: O(n^2) and the indices shift underneath you. - Swapping zeros to the front: the relative order of the non-zero elements must be preserved, so zeros go to the end.
- Forgetting the padding pass: the slots after
kstill hold stale values, so they must be zeroed (or, in the swap variant, they are already zeros). - Comparing with
is 0: use== 0, sinceiscompares identity.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Two Pointers Problems
中文速览与面试要点
移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。请注意,必须 原地 对数组进行操作,不能拷贝额外的数组。尽量减少操作次数。约束:1 ≤ nums.length ≤ 10^4;-2^31 ≤ nums[i] ≤ 2^31 − 1。
核心要点
- 读写双指针(标准解) :k 为「下一个非零元素的落点」。遍历数组,遇到非零就写到 nums[k] 并令 k += 1 。
- 末尾补零 :遍历结束后,把 nums[k:] 全部置 0。
- 为什么相对顺序不变 :非零元素按遍历顺序依次写入,天然保持了原相对顺序。
- 优化 · 交换法 :也可以让 k 只在遇到非零时前进,并把 nums[k] 与 nums[i] 交换——这样零会被自动「挤」到后面,无需第二次遍历。
常见陷阱
- 用 nums.remove(0); nums.append(0) :remove 是 O(n) 查找 + O(n) 搬移,整体退化为 O(n²)。
- 用 sorted(nums, key=lambda x: x == 0) :会创建新数组,违反「原地」要求。
- 忘记末尾补零 :只搬移非零元素会让数组末尾残留旧值(重复的非零元素)。
- 用 while 0 in nums 循环删除 : in 是 O(n),整体 O(n²)。
参考实现
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
k = 0 # 下一个非零元素的落点
for x in nums:
if x != 0:
nums[k] = x
k += 1
for i in range(k, len(nums)): # 剩余位置补零
nums[i] = 0
# 交换法(单次遍历,但交换次数更多):
# k = 0
# for i in range(len(nums)):
# if nums[i] != 0:
# nums[i], nums[k] = nums[k], nums[i]
# k += 1