)
一、题目要求给定一个数组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).