移动零

作者: fan_8209 | 来源:发表于2021-08-19 10:38 被阅读0次

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

啊,我想用双指针,各种特殊情况满足不了。脑子清醒点再补上

var moveZeroes = function(nums) {
    let index = 0//设置一个计数器
    nums.forEach((num)=>{//遍历数组非0元素赋给计数器位置
        if(num!=0){
            nums[index] = num
            index++
        }
    })
    //遍历结束后将计数器之后的值赋为0
    for(let i=index;i<nums.length;i++){
        nums[i] = 0
    }
    console.log(nums)
    console.log(index)
    return nums
};
moveZeroes([1,0])

冒泡:

var moveZeroes = function(nums) {
    for(let j=1;j<nums.length;j++){
        for(let i=1;i<nums.length;i++){
            if(nums[i-1]==0){ //遇到0元素向右交换位置
                let temp = nums[i-1]
                nums[i-1] = nums[i]
                nums[i] = temp
            }
        }
    }
    console.log(nums)
    return nums
};

相关文章

  • 【移动零】

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

  • 移动零

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

  • 移动零

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

  • 移动零

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

  • 移动零

    题目描述:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例:输...

  • 移动零

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/perf...

  • 移动零

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

  • 移动零

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

  • 移动零

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

  • 移动零

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

网友评论

      本文标题:移动零

      本文链接:https://www.haomeiwen.com/subject/nykjlltx.html