快慢指针
解题思路
-
slow、fast 指针起初都指向数组的第一项,遇到第一个 0 的元素时,slow 停下,fast 继续向后走找到一个不为 0 的元素索引
-
左指针为 0 且 右指针不为 0 => 交换位置(0 被放到了后面);
-
重复以上的步骤,直到 fast 指针走到数组最后一位结束;
复杂度
-
时间复杂度:
O(n)
-
空间复杂度:
O(1)
实现代码
var moveZeroes = function (nums) {
if (nums.length === 1) {
return nums;
}
let left = 0;
let right = 0;
while (left <= right && right < nums.length) {
// 左指针为 0 且 右指针不为 0 => 交换位置(0 被放到了后面)
if (nums[right] !== 0 && nums[left] === 0) {
[nums[left], nums[right]] = [nums[right], nums[left]];
}
// left、right 指针一直向右走,找到第一个 0 的位置,右指针向右走,左指针停下
if (nums[left] !== 0) {
left++;
}
right++;
}
};
移动非 0 元素
解题思路
-
遍历数组,把 非 0 元素从数组第一项开始替换;
-
遍历结束后替换到了 M 项,则 M 项之后的位置全部填 0 即可;
复杂度
-
时间复杂度:
O(n)
-
空间复杂度:
O(1)
实现代码
var moveZeroes = function (nums) {
let i = 0;
for (let index = 0; index < nums.length; index++) {
const el = nums[index];
if (el !== 0) {
nums[i++] = el;
}
}
// 处理全是 0 的情况
if (i === 0) {
return;
}
while (i < nums.length) {
nums[i++] = 0;
}
}
leetcode🧑💻 977. 有序数组的平方
上一篇