Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
給予一個整數陣列 nums,移動所有的 0 到最末位,同時維持原本的陣列數值位置。
Example 1:
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2:
Input: nums = [0] Output: [0]
Solution:
1. 宣告 index = 0。
2. 執行 i 長度的迴圈。
3. 如果陣列中的數值不是 0,則前後交換位置。
4. 如果 i 是 0 的話,則不變動,往下搜尋,並由 index 來將 0 替換至後方。
5. 回傳 nums。
Code 1: BigO(n)
var moveZeroes = function(nums) { let index = 0 for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { [nums[i], nums[index]] = [nums[index], nums[i]] index++ } } return nums; };
FlowChart:
Example 1
Input: nums = [0,1,0,3,12] i, index, nums[i], nums[index] 0 0 0 0 1 0 1 0 2 1 0 0 3 1 3 0 4 2 12 0 [ 1, 3, 12, 0, 0 ]
Example 2
Input: nums = [0] i, index, nums[i], nums[index] 0 0 0 0 [ 0 ]
Solution:
1. 執行 i 長度的迴圈。
2. 執行 j 長度的迴圈。
3. 如果陣列中的數值是 0,則宣告 box 來暫存 nums[i] 位置的數值,將 nums[i] 變更為 nums[j],最後將 nums[j] 變為 box。
4. 回傳 nums。
Code 2: BigO(n^2)
var moveZeroes = function(nums) { for (let i = 0; i < nums.length - 1; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] === 0) { let box = nums[i] nums[i] = nums[j] nums[j] = box } } } return nums; };