0
点赞
收藏
分享

微信扫一扫

移动零(JS)

纽二 2022-02-08 阅读 21

在这里插入图片描述
题目来源于leetcode移动0

var moveZeroes = function(nums) {
    //双重for循环
    for(let i = 0; i < nums.length - 1; i++){
        for(let j = 0 ; j < nums.length -1 ;j++){
            if(nums[j] == 0){
                nums[j] = nums[j+1]
                nums[j+1] = 0
            }
        }
    }

    //快慢指针
    let fast = 0 , slow = 0;
    while(fast < nums.length){
        if(nums[fast] != 0){
            nums[slow++] = nums[fast]
        }
        fast++
    }

    while(slow<nums.length){
        nums[slow++] = 0
    }

    // 使用API
    let n = nums.length
    let arr =  nums.filter(item=>item!=0)
    arr = arr.concat(new Array(n-arr.length).fill(0))
    for(let i = 0 ; i < n; i++){
        nums[i] = arr[i]
    }

};
举报

相关推荐

283 移动零

JAVA 移动零

283. 移动零

力扣-移动零

283-移动零

0 条评论