Last active
October 15, 2017 17:38
-
-
Save cixuuz/7e360c39c8b9f5dbc258913286501d47 to your computer and use it in GitHub Desktop.
[283. Move Zeroes] #leetcode
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
class Solution(object): | |
# O(n) O(1) | |
def moveZeroes(self, nums): | |
""" | |
:type nums: List[int] | |
:rtype: void Do not return anything, modify nums in-place instead. | |
""" | |
i = 0 | |
j = 0 | |
while j < len(nums): | |
while i < len(nums) and nums[i] != 0: | |
i += 1 | |
if j > i and nums[j] != 0: | |
nums[i], nums[j] = nums[j], nums[i] | |
j += 1 | |
class Solution(object): | |
# same method different way | |
def moveZeroes(self, nums): | |
""" | |
:type nums: List[int] | |
:rtype: void Do not return anything, modify nums in-place instead. | |
""" | |
lastNonZeroFoundAt = 0 | |
for cur in range(len(nums)): | |
if nums[cur] != 0: | |
nums[cur], nums[lastNonZeroFoundAt] = nums[lastNonZeroFoundAt], nums[cur] | |
lastNonZeroFoundAt += 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment