算法(TS):移动零

255 阅读1分钟

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

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

输入: nums = [0,1,0,3,12] 输出: [1,3,12,0,0]

示例 2:

输入: nums = [0] 输出: [0]

提示:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

进阶: 你能尽量减少完成的操作次数吗?

解法一

遍历 nums,将 0 从中移除,并记录 0 的个数,遍历结束创建一个元素全部为0的数组,将其 push 到 nums 中

function moveZeroes(nums: number[]): void {
    let zeroCount = 0
    let i = nums.length - 1
    while(i > -1) {
        if (nums[i] === 0) {
            nums.splice(i,1)
            zeroCount ++
        }
        i--
        
    }
    const zeroArr = new Array(zeroCount)
    nums.push(...zeroArr.fill(0,0,zeroCount))
};

解法二

把非 0 的元素往前移动。 变量 index 表示上一次移动非 0 的下标,初始值为 0。遍历 nums 当遇到非 0 的时候,将其移动到 index 的位置,并将 index ++,当 nums 遍历结束,将index ~ nums.length 的元素填为 0

/**
 Do not return anything, modify nums in-place instead.
 */
function moveZeroes(nums: number[]): void {
    const len = nums.length
    let index = 0
    for(let i = 0;i < len; i++) {
        if (nums[i] !== 0) {
            nums[index] = nums[i]
            index++
        }
    }

    while(index < len) {
        nums[index] = 0
        index ++
    }
};