Skip to content

LeetCode题解:283. 移动零,JavaScript,一次遍历,详细注释 #105

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/move-zeroes/

参考题解了动画演示 283.移动零的一次遍历解法。

解题思路:

  1. 快指针遍历数组。慢指针表示存放非0元素的位置
  2. 快指针遍历到非0元素时,将其移动到慢指针位置,并将慢指针加1

时间复杂度:O(n)
空间复杂度:O(1)

/**
 * @param {number[]} numbers
 * @return {void} Do not return anything, modify numbers in-place instead.
 */
var moveZeroes = function (numbers) {
  // 非零值需要移动到的位置,其位置始终是最前一个待安放非零元素的位置
  let moveIndex = 0;

  numbers.forEach((value, index) => {
    // 如果当前值不为0,则需要将其向前移动
    if (value !== 0) {
      // 避免特殊情况,如数组只有1个值时,将其值错误赋值为0
      if (moveIndex !== index) {
        // 将当前值移动到前排
        numbers[moveIndex] = value;
        // 将当前值设置为0,完成值的对调
        numbers[index] = 0;
      }
      // 移动完之后,将指针移动到下一个需要移动的位置
      moveIndex++;
    }
  });
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions