Skip to content

Latest commit

 

History

History
59 lines (48 loc) · 1.52 KB

283.移动零.md

File metadata and controls

59 lines (48 loc) · 1.52 KB

283.移动零

/*
 * @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

解法 1: 双指针

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
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]]
  }
}

解法 2: 滚雪球

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

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]
  }
}

Case

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)
})