給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說明:
必須在原數組上操作,不能拷貝額外的數組。
儘量減少操作次數。
代碼
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let fastIndex = 0;
let slowIndex = 0;
while(fastIndex<nums.length){
if(nums[fastIndex] != 0){
if(nums[slowIndex] == 0){
nums[slowIndex] = nums[fastIndex];
nums[fastIndex] = 0
}
slowIndex ++;
}
fastIndex++;
}
return nums
};