LeetCode 283. 移动零

283. 移动零

解题思路

把非零元素移动到前面,剩下的位置填充零。使用双指针,一个指针遍历数组,另一个指针记录非零元素的位置。

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public void moveZeroes(int[] nums) {
int cnt = 0;
for(int i = 0; i < nums.length; i ++) {
if(nums[i] != 0) {
nums[cnt++] = nums[i];
}
}

for(int i = cnt; i < nums.length; i ++) {
nums[i] = 0;
}
}
}

LeetCode 283. 移动零
https://sowink.cn/2026/02/08/LeetCode-283-移动零/
作者
Xurx
发布于
2026年2月8日
许可协议