Created
June 23, 2023 13:46
-
-
Save karmatr0n/1bab0ddaebaff6d80b426f223f5030f9 to your computer and use it in GitHub Desktop.
Move all zeros to the end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def move_zeros(nums) | |
return nums if nums.empty? | |
left = 0 | |
right = nums.length - 1 | |
while left < right do | |
if nums[left] == 0 | |
nums[left], nums[right] = nums[right], nums[left] | |
right -= 1 | |
else | |
left += 1 | |
end | |
end | |
nums | |
end | |
nums = [0, 1, 0, 0, 0, 0, 1, 2, 3, 4, 0, 1, 5, 7 ] | |
result = move_zeros(nums) | |
puts result.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment