Typescript-Algorithms
    Preparing search index...

    Variable move_zeroesConst

    move_zeroes: (nums: number[]) => void = moveZeroes

    283.移动零

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

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


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


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


    • 1 <= nums.length <= 10^4
    • -2^31 <= nums[i] <= 2^31 - 1

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

    Type declaration

      • (nums: number[]): void
      • Do not return anything, modify nums in-place instead.

        Parameters

        • nums: number[]

        Returns void

    • 将left左边区域看作全是非0的区域,一开始left在整个数组的最左边。
    • 我们遍历数组,如果当前元素不为0,则将当前元素和left位置的元素交换,然后left++。如果当前元素为0,则跳过
    • 遍历结束后,left左边的区域全是非0的元素。
    function moveZeroes(nums: number[]): void {
    let l = 0;

    for (let i = 0; i < nums.length; i++) {
    if (nums[i] !== 0) {
    [nums[l], nums[i]] = [nums[i], nums[l]];
    l++;
    }
    }
    };