11-LeetCode 热题 100 283. 移动零(一行一注释)

13 阅读1分钟

一、题目

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

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

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

示例 2:

输入: nums = [0]
输出: [0]

提示:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

进阶: 你能尽量减少完成的操作次数吗?

解答+一行一注释

两个方案:

1.直接倒序遍历,然后splice+push

2.遍历使用双指针

/** 直接倒序遍历,splice+push */
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    // 获取数组长度
    let len = nums.length
    // 如果len不为0就继续循环,执行一次之后len-1
    while(len--){
        // 如果当前值为0
        if(nums[len] === 0){
            // 删除当前0
            nums.splice(len,1)
            // 在数组后面push一个0
            nums.push(0)
        }
    }
};

/** 快慢指针 */
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    // 设置一个指针,初始值为0,也就是指向数组第一项
    let pnt = 0
    // 遍历数组
    for(let i = 0 ;  i < nums.length; i++){
        // 如果当前值不是0
        if(nums[i]!==0){
            // 将pnt和i所指向的值交换
            [nums[pnt],nums[i]] = [nums[i],nums[pnt]]
            // 交换后移动pnt指针
            pnt++
            // 上述这两步本质的目的就是将所有不是0的都移动到数组左边,所以数组右边自然都会是0了
        }
    }
};