LeetCode: Move Zeroes

Question

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array. Minimize the total number of operations.

Solution

首先把 nums (Array 型態) 中有幾個零,記錄在 zero_counter。接著用 select! 方法將不是零的數字依序抓出來,最後在 while loop 裡面用 push 方法逐個地往後塞就可以了。

注意:select! 與 select 不同的是 select! 會改變 nums 原有的集合元素。

def move_zeroes(nums)
  zero_counter = nums.count(0)
  nums.select! do |num|
    num != 0
  end
  i = 0
  while i < zero_counter
    nums.push(0)
    i += 1
  end
  nums
end