Ruby Solution


  • 0
    I

    I use a sentinel st as the start of the zero range, just swap them if meeting a nonzero element.

    def move_zeroes(nums)
      # st stands for the start of zero range
      st = -1
    
      nums.each_with_index do |ele, i|
        if st == -1
          if ele.zero?
            st = i
          end
        else
          if ele.nonzero?
            swap(nums, st, i)
            st += 1
          end
        end
      end
    
      nums
    end
    
    def swap(nums, i, j)
      tmp = nums[i]
      nums[i] = nums[j]
      nums[j] = tmp
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.