一、题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素
的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
二、示例
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
输入: nums = [0]
输出: [0]
三、思路
遍历全部的元素,将数值不为0的全部转移到前面,最后再将没有覆盖的元素的值设置为0,时间复杂度为O( n ),空间复杂度为O( 1 )。
四、代码展示
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
let length = nums.length
let curIndex = 0
for (let i = 0; i < length; i++) {
if(nums[i] !== 0) {
nums[curIndex] = nums[i]
curIndex++
}
}
for(let j = curIndex; j < length; j++) {
nums[j] = 0
}
return nums
};
五、总结