題目鏈接:https://leetcode.cn/problems/move-zeroes/?envType=study-plan-v2&envId=top-100-liked
解題思路:使用雙指針,除了0之外的數(shù)字是一個(gè)相對(duì)有序的數(shù)組所以只需要交換數(shù)字的位置就可以達(dá)到排序的效果,其余位數(shù)用0補(bǔ)全
/**
* @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的進(jìn)行排序
if (nums[right] !== 0) {
nums[left] = nums[right]
left++
}
right++
}
// 等于0 的進(jìn)行補(bǔ)全即可
while (left < nums.length) {
nums[left] = 0
left++
}
return nums
};
const res = moveZeroes([0,1,0,3,12])
console.log(res)