移动零

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

示例:

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

说明:

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

由于必须在原数组上操作,而replace方法会返回一个新数组,所以不能用。。只能遍历数组,找到零并删除同时在末尾添加零。。

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    let r = [];
    for(let l = 0,r = nums.length - 1; l < r;) {
        if (nums[l] === 0) {
            nums.splice(l, 1);
            nums.push(0);
            r--; 
        } else {
            l++;
            continue;
        }
    }
};

 

posted @ 2019-07-17 15:20  湛蓝的家  阅读(113)  评论(0编辑  收藏  举报