Easy solution in ruby, 3 lines with O(1) space. How can i use accumulator?


  • 0
    A
    def move_zeroes(nums)
      zc=0
      nums.each_with_index{|n,i| n==0 ? (zc+=1) : (nums[i-zc]=n)} ## i-zc is offset
      (nums.size-zc).upto(nums.size-1){|i| nums[i]=0}
    end
    

    how to use inject(?) or other method in this solution?

    We can solve this problem by swap method, but i think that way will consume too much time for write.


  • 0

    Don't know about a really different way, but you could replace your third line with one of these:

    nums.fill(0, nums.size-zc)
    nums.fill(0, -zc) if zc > 0
    

Log in to reply
 

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