【leetcode初级算法JS实现】8.移动零

在这里插入图片描述

// 解法1:
// 从头开始遍历,遇到0就去除;
// 循环结束时,比较新旧数组的长度,补充0
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    
    
    let oldLen = nums.length;
    for(let i = oldLen-1; i--; i >= 0){
    
    
        if(nums[i] === 0){
    
    
            nums.splice(i, 1);
        }
    }
    let newLen = nums.length;
    for(let i = 0; i< oldLen- newLen; i++) nums.push(0);
};
// 解法2:
// 使用指针p, p初始化为0, 遍历数组时,若当前项不为0,则nums[p]记录,并p++;
// 循环结束时,不为0的项都在数组的前面;
// 这时候只要将p后面的数字用fill变为0就OK
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    
    
    let p = 0;
    let oldLen = nums.length
    for(let i = 0; i< oldLen; i++){
    
    
        if(nums[i] !== 0){
    
    
            nums[p] = nums[i];
            p++
        }
    }
    nums.fill(0, p, oldLen);
};

猜你喜欢

转载自blog.csdn.net/qq_34086980/article/details/106419483