Skip to main content

移动零

题目

给定一个数组 nums, 编写一个函数将所有 0 移动到数组的末尾, 同时保持非零元素的相对顺序, 必须在原数组上操作, 不能拷贝额外的数组.

提示:
  • 1 <= nums.length <= 10⁴
  • -2³¹ <= nums[i] <= 2³¹ - 1
示例

输入: [0, 1, 0, 3, 6]

输出: [1, 3, 6, 0, 0]

题解

fast            fast            fast            fast            fast            fast
↓ ↓ ↓ ↓ ↓ ↓
[0 1 0 3 6] [0 1 0 3 6] [1 0 0 3 6] [1 0 0 3 6] [1 3 0 0 6] [1 3 6 0 0]
↑ ↑ ↑ ↑ ↑ ↑
slow slow slow slow slow slow
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
const n = nums.length
let slow = 0,
fast = 0

while (fast < n) {
if (nums[fast] !== 0) {
;[nums[slow], nums[fast]] = [nums[fast], nums[slow]]
slow++
}
fast++
}
}