LeetCode 283. Move Zeroes All In One
array
in-place
swap / 数组就地交换
算法
errors
function moveZeroes(nums: number[]): void {
// in-place 就地交换
let index = 0;
// let flag = false;
for(let i = 0; i < nums.length; i++) {
if(nums[i] === 0) {
index = i;
flag = true;
console.log(`index =`, index);
} else {
// nums[index] !== 0
console.log(`flag =`, flag);
if(flag) {
// swap
[
nums[index],
nums[i]
] = [
nums[i],
nums[index]
];
index = i;
console.log(`nums =`, nums);
// clear
flag = false;
}
}
}
};
solutions ✅
/**
Do not return anything, modify nums in-place instead.
*/
function moveZeroes(nums: number[]): void {
// in-place 就地交换
for(let i = 0; i < nums.length - 1; i++) {
let j = i + 1;
while(nums[j] === 0 && j < nums.length - 1) {
j += 1;
}
// console.log(`j`, j, nums[j])
if(nums[i] === 0) {
// swap
[
nums[j],
nums[i]
] = [
nums[i],
nums[j]
];
}
}
};
demos
https://leetcode.com/problems/move-zeroes/description/?envType=study-plan-v2&envId=leetcode-75
https://leetcode.com/problems/move-zeroes/solutions/5204027/leetcode-283-move-zeroes-solution/