283. Move Zeroes
- Total Accepted: 127538
- Total Submissions: 272915
- Difficulty: Easy
- Contributors: Admin
Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Code
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# maintain how many zeroes we have seen
count0 = 0
for idx, v in enumerate(nums):
if v != 0:
if count0 > 0:
nums[idx-count0] = v
nums[idx] = 0
else:
count0 += 1
Idea
An element should be moved count0 ahead, where count0 records how many zeroes we have seen.
If the order of non-zero elements is not required to maintain, we can have another algorithm:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
start, end = 0, len(nums)-1
while start < end:
if nums[start] == 0:
nums[start], nums[end] = nums[end], nums[start]
end -= 1
else:
start += 1