欣迪

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 的數量,加到最後面。

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。