283. 移动零
- 题号:283
- 来源:LeetCode
- 难度:简单
- 标签:
数组原地算法双指针 - 语言:TypeScript · Python
- 解法:2 个
- 作者:lmliheng
- 最近更新:2026-09-29
TypeScript
TypeScript · O(n^2) 时间 · O(1) 空间 · 更新于 2026-09-27
splice 就地删零,最后在数组末尾补齐
typescript
/**
* @difficulty easy
* @tags 数组,原地算法
* @time O(n^2)
* @space O(1)
* @note splice 就地删零,最后在数组末尾补齐
* @283. 移动零
*/
let nums = [0, 1, 0, 3, 12]
let zeroCount = 0
for (let i = 0; i < nums.length; i++) {
console.log(i)
if (nums[i] === 0) {
nums.splice(i, 1)
zeroCount++
i--
}
}
nums.push(...new Array(zeroCount).fill(0))
console.log(nums)Python
Python · O(n) 时间 · O(1) 空间 · 更新于 2026-09-29
倒序删除 0 再在末尾补齐,原地修改
python
"""
@difficulty easy
@tags 数组,双指针,原地算法
@time O(n)
@space O(1)
@note 倒序删除 0 再在末尾补齐,原地修改
移动零
lc 283
"""
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_num=0
zero_index=[]
for i in range(len(nums)-1, -1, -1):
if nums[i] == 0:
zero_num += 1
nums.pop(i)
nums.extend([0]*zero_num)源码:python/leetcode/hot100/4.py
在 GitHub 上查看题目所在目录:lmliheng/algorithm