Skip to content

Instantly share code, notes, and snippets.

@zacwasielewski
Last active August 18, 2020 01:16
Show Gist options
  • Save zacwasielewski/663f1f688c8689fd2aec5b2412dbe753 to your computer and use it in GitHub Desktop.
Save zacwasielewski/663f1f688c8689fd2aec5b2412dbe753 to your computer and use it in GitHub Desktop.
Rendezvous with cassidoo question of the week – August 27th, 2020
# Given an array of random integers, move all the zeros in the array
# to the end of the array. Try to keep this in O(n) time (or better)!
#
# Example:
#
# $ moveZeros([1, 2, 0, 1, 0, 0, 3, 6])
# $ [1, 2, 1, 3, 6, 0, 0, 0]
# This is prettier! :)
def moveZeros(nums)
nums.partition{|n| n > 0}.flatten
end
# But this is faster :(
def moveZeros(nums)
nums.select{|n| n > 0} + nums.select{|n| n.zero?}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment