LeetCode 283. 移动零
原题链接
简单
public class Solution {
public void moveZeroes(int[] nums) {
int length;
// 先来做一个前置校验,不满足条件的入参直接返回
if (nums == null || (length = nums.length) == 0) {
return;
}
// 双指针:firstZeroPlace始终记录第一个0元素的位置,初始该位置可能不为零,
// 但是判断到 nums[i] != 0 并且 i > firstZeroPlace 时为0
int firstZeroPlace = 0;
// 找到不为0的元素,放到firstZeroPlace的地方,firstZeroPlace往前推进
for (int i = 0; i < length; i++) {
if (nums[i] != 0) {
// 找到不为0的元素,与firstZeroPlace替换,即与0替换
if (i > firstZeroPlace) {
nums[firstZeroPlace] = nums[i];
nums[i] = 0;
}
// firstZeroPlace往前推进
firstZeroPlace++;
} else {
// firstZeroPlace记录第一个0值,不用执行++操作
}
}
}
}