Created
September 1, 2015 20:24
-
-
Save afternoon/9b6552fa5924d8105428 to your computer and use it in GitHub Desktop.
Given an array of numbers (1,2,3,8,0,2,2,0,10), move all 0s to the right end and all other numbers to the left while keeping relative order of non-zero numbers. Has to be linear in time and in-place.
This file contains hidden or 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 separate_zeroes(nums): | |
''' | |
Given an array of numbers (1,2,3,8,0,2,2,0,10), move all 0s to the right end and all other numbers to the left while keeping relative order of non-zero numbers. Has to be linear in time and in-place. | |
>>> separate_zeroes([1, 2, 3, 8, 0, 2, 2, 0, 10]) | |
[1, 2, 3, 8, 2, 2, 10, 0, 0] | |
>>> separate_zeroes([1, 1, 1, 0, 1, 0, 0, 1]) | |
[1, 1, 1, 1, 1, 0, 0, 0] | |
>>> separate_zeroes([0]) | |
[0] | |
>>> separate_zeroes([0, 0, 1]) | |
[1, 0, 0] | |
>>> separate_zeroes([0, 0, 0, 1, 0, 0, 0]) | |
[1, 0, 0, 0, 0, 0, 0] | |
''' | |
num_zeroes = 0 | |
zero_to_swap = None | |
for i in range(0, len(nums)): | |
if nums[i] == 0: | |
if zero_to_swap is None: | |
zero_to_swap = i | |
else: | |
if zero_to_swap is not None: | |
nums[zero_to_swap] = nums[i] | |
nums[i] = 0 | |
zero_to_swap = i | |
return nums | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment