Given an integer array nums
, move all 0
‘s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Ex1. Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Ex2. Input: nums = [0] Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
var moveZeroes = function(nums) { let zeros = 0 let startAt = 0 while(nums.indexOf(0, startAt) !== -1 ) { const idx = nums.indexOf(0, startAt) nums.splice(idx, 1) zeros++ startAt = idx } for(let i = 0; i < zeros; i++) { nums.push(0) } };
思路
這題的困難點在於不能複製另一個 Array 來操作。如果使用 for loop 去移除 0 會造成 陣列長度的改變,影響其結果。
這邊用了 indexOf 的函數做操作, indexOf 的第二個參數是搜尋的起始值,使用 while loop 時可以不再重複檢查參數。最後再計算所有被減去的 0 的數量,加到最後面。