Given an integer array nums
, move all 0
to the end of the it while maintaining the relative order of the non-zero elements.
Constraints:
- You must do this in-place without making a copy of the array.
- $1\leq nums.length \leq 104$
- $-231 \leq nums[i] \leq 231-1$
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Input: nums = [0] Output: [0]Again, let’s first consider the trivial case where
len(nums) == 1
. We don’t need to do anything in this case.
In general, we will have to at least scan nums
once.
def moveZeroes(nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
poses = []
for i, n in enumerate(nums):
if n == 0:
poses.append(i)
for i, pos in enumerate(poses):
# we use pos-i because we moved i number of zeros to the end
nums.append(nums.pop(pos-i))
# tests
nums = [0]
moveZeroes(nums)
print(nums == [0])
nums = [0, 1]
moveZeroes(nums)
print(nums == [1, 0])
nums = [0, 1, 2, 0]
moveZeroes(nums)
print(nums == [1, 2, 0, 0])
nums = [1, 2 ]
moveZeroes(nums)
print(nums == [1, 2])
O(n)
, one full scan.
O(n)
, potentially nums
can be all zeroes so len(poses) == len(nums)
.
nil
.
<<imports for typing>>