xiqe / code-train

前端算法

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

移动零

xiqe opened this issue · comments

移动零

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

示例:

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

说明:

  • 必须在原数组上操作,不能拷贝额外的数组。
  • 尽量减少操作次数。

reply

var moveZeroes = function(nums) 
    // 设置一个计数器
    let len = 0;
    for(let i=0;i<nums.length;i++){
        // 如果计数器等于nums的length,说明所有项都遍历完成,跳出
        if(len == nums.length){
            return nums
        }
        // 如果nums[i]为0,则清除当前项,并且在最后添加0,i--
        if(nums[i]==0){
            nums.splice(i,1);
            nums.push(0);
            i--
        }
        // 每循环一次,计数器+1
        len++;
    }
};