一、题目要求
给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。
请注意,必须在不复制数组的情况下原地对数组进行操作。
二、题目解法
1.双指针(快慢指针)
思路:用slow指针指向下一个非零元素应该放置的位置,用fast指针遍历数组,遇到非零元素就交换到slow位置。
代码如下:
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function(nums) { let slow = 0; for(let fast = 0; fast < nums.length; fast++){ if(nums[fast] !== 0){ [nums[slow], nums[fast]] = [nums[fast], nums[slow]]; slow++; } } };此代码时间复杂度为O(n).
2.两次遍历(覆盖法)
思路:第一次遍历把所有非零元素按顺序移到数组前面,第二次遍历把剩余位置全部置为 0。
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function(nums) { let index = 0; // 记录非零元素放置的位置 // 第一次遍历:将所有非零元素移到前面 for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { nums[index] = nums[i]; index++; } } // 第二次遍历:从 index 开始将剩余位置全部置为 0 for (let i = index; i < nums.length; i++) { nums[i] = 0; } };此代码时间复杂度为O(n).