leetcode题解-移动零

代码

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

思路

遍历,遇到0的时候删除在末尾添加0。指针向前移动一位,所需遍历的长度减少一位。

猜你喜欢

转载自blog.csdn.net/weixin_38616850/article/details/106307872
今日推荐