题目链接:https://leetcode.cn/problems/move-zeroes/?envType=study-plan-v2&envId=top-100-liked
解题思路:使用双指针,除了0之外的数字是一个相对有序的数组所以只需要交换数字的位置就可以达到排序的效果,其余位数用0补全
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let left = 0
let right = 0
while (right < nums.length) {
// 判断了不等于0的进行排序
if (nums[right] !== 0) {
nums[left] = nums[right]
left++
}
right++
}
// 等于0 的进行补全即可
while (left < nums.length) {
nums[left] = 0
left++
}
return nums
};
const res = moveZeroes([0,1,0,3,12])
console.log(res)