算法题-移动零【JS实现】

移动零


给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

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

思路(方案):

  1. 遍历数组,将0全部去掉,然后用0填充数组
  2. 利用指针,交换元素位置

方案一

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    
    
    if (!nums || !nums.length) return;
    let j = 0;
    for (let i = 0; i < nums.length; i++) {
    
    
        if(nums[i]) {
    
    
            nums[j++] = nums[i];
        }
    }
    for (; j < nums.length; j++) {
    
    
        nums[j] = 0;
    }
};

方案二

var moveZeroes = function(nums) {
    
    
    if (!nums || !nums.length) return;
    for (let i = 0, j = 0; i < nums.length; i++) {
    
    
        if(nums[i]) {
    
    
            [nums[j++], nums[i]] = [nums[i], nums[j]];
        }
    }
};

猜你喜欢

转载自blog.csdn.net/baidu_33591715/article/details/108417247