/*
* @lc app=leetcode.cn id=283 lang=typescript
*
* [283] 移动零
*/
// @lc code=start
/**
Do not return anything, modify nums in-place instead.
*/
function moveZeroes(nums: number[]): void {}
// @lc code=end
function moveZeroes(nums: number[]): void {
let j = 0
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) [nums[i], nums[j++]] = [nums[j], nums[i]]
}
}
https://leetcode.com/problems/move-zeroes/discuss/172432
function moveZeroes(nums: number[]): void {
let offset = 0
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 0) offset++
else if (offset !== 0) [nums[i - offset], nums[i]] = [nums[i], 0]
}
}
test.each([
{ input: { nums: [0, 1, 0, 3, 12] }, output: [1, 3, 12, 0, 0] },
{ input: { nums: [1, 0, 3, 0, 5, 0] }, output: [1, 3, 5, 0, 0, 0] },
])('input: nums = $input.nums', ({ input: { nums }, output }) => {
moveZeroes(nums)
expect(nums).toEqual(output)
})