移动零

双指针一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
const length = nums.length;
// 双指针
let left = 0,
right = 0;
while (left < length && right < length) {
// left找到一个等于0的位置
while (nums[left] !== 0 && left < length) {
left++;
}
right = left;
// right找到一个不等于0的位置
while (nums[right] === 0 && right < length) {
right++;
}
if (left >= length || right >= length) break;
nums[left] = nums[right];
nums[right] = 0;
}
// console.log("🚀 ~ moveZeroes ~ nums:", nums);
return nums;
};
// moveZeroes([0, 1, 0, 3, 12]);
// moveZeroes([1]);
// moveZeroes([1, 0, 1]);

双指针二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
const len = nums.length;
let left = 0,
right = 0;
while (right < len) {
if (nums[right]) {
// 交换
const temp = nums[right];
nums[right] = nums[left];
nums[left] = temp;
left++;
}
right++;
}
console.log("🚀 ~ moveZeroes ~ nums:", nums);
return nums;
};
moveZeroes([0, 1, 0, 3, 12]);

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。