283.移动零

2020-04-21
移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非

零元素的相对顺序。

题解:
思路1:双指针
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function (nums) {
  let i = 0, j = nums.length - 1; // 双指针
  while (i < j) {
    if (nums[i] === 0) { // 如果i下标等于0 那么删掉这一项
      nums.splice(i, 1);
      nums.push(0); // 删掉后在末尾补0
      j--; // 右指针左移一位
    } else {
      i++; // 不等于0右指针右移1位
    }
  }
  return nums;
};
原文地址:https://www.cnblogs.com/lanpang9661/p/12742252.html