移动零
移动零
#resource / algorithm
#type / snippet
#status / evergreen
#source / leetcode
#algo / two-pointers
#ds / array
[!info] related notes 算法面试题型 MOC 双指针
移动零
解法
原地栈
var moveZeroes = function(nums) {
let index = 0;
for (const a of nums) {
if (a === 0) {
continue
} else {
nums[index] = a;
index++;
}
}
while(index < nums.length) {
nums[index] = 0;
index++
}
};
双指针
var moveZeroes = function(nums) {
// 左指针用于确定下一个非零数的位置,右指针去遍历每一个数,把非零数放到左指针处。
let zeroIndex = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
[nums[zeroIndex], nums[i]] = [nums[i],nums[zeroIndex]]
zeroIndex++;
}
}
};