leetcode 283. 移动零 JavaScript双指针

leetcode中很多有关数组的题目都可以用双指针解决,例如之前做的一道要求在原地(in-place)移除元素就是用双指针做的 LeetCode 27. 移除元素 – 昨日当年

使用思路是:在需要进行原地操作的题中 声明两个指针, 一个指针用来作索引正常遍历,另一个指针指向需要做替换操作的元素

就比如这道 Move Zeroes

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

i 作 index 用来遍历 nums

找到非0元素时 把值赋给 nums[j]

则在 for 循环结束时 nums[0] 至 nums[j] 为非0元素

即数组中存在 j+1 个非0元素 ,然后用原本数组的长度(i+1)减去非0元素 剩下的赋为0就行了

Move Zeroes

Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.