作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2ba4i/ 来源:力扣(LeetCode)

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题目

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

示例:

输入: [0,1,0,3,12]

输出: [1,3,12,0,0]

说明:

  • 必须在原数组上操作,不能拷贝额外的数组。
  • 尽量减少操作次数。

相关标签:
数组 双指针

题解

思路:从后往前遍历,如果是0直接删除并在末尾push一个0

  1. /**
  2. * @param {number[]} nums
  3. * @return {void} Do not return anything, modify nums in-place instead.
  4. */
  5. var moveZeroes = function(nums) {
  6. for (let i = nums.length - 1; i >= 0; i--) {
  7. if (nums[i] === 0) {
  8. nums.splice(i, 1);
  9. nums.push(0);
  10. }
  11. }
  12. };

参考:
https://leetcode-cn.com/problems/move-zeroes/solution/yi-dong-ling-by-leetcode-solution/