「每日LeetCode」2020年11月19日

本文最后更新于:2023年3月19日 晚上

Lt283. 移动零

283. 移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:

1
2
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。

思路

双层遍历(冒泡)

很显然可以得到一种解法,类似冒泡,遍历每一个元素,如果当前是 0 将它与它之后第一个非 0 元素交换位置。最后可以将 0 都冒泡到数组尾部。

一次遍历

使用一个 index 记录非 0 的数要排在第几个,每次设置非 0 的元素都令 index++。遍历完数组以后,将剩余的位置全部设为 0 即可。

解答

双层遍历(冒泡)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 0) {
let index = i + 1;
while (index < nums.length && nums[index] === 0) index++;
if (index < nums.length) [nums[i], nums[index]] = [nums[index], nums[i]];
}
}
return nums;
};

一次遍历

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
let index = 0;
for (const num of nums) {
if (num) nums[index++] = num;
}
while (index < nums.length) nums[index++] = 0;
return nums;
};