Leetcode: Move zeros
The task is as follows: Given an integer array nums
, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
The last note is actually the important part. Without this, it would be easy to just use array splitting in Python and add a zero. This would look similar to this:
if nums[pos] == 0:
nums = nums[:pos] + nums[pos+1:] + [0]
nums
and the change is no longer in place. The next best solution that I found was to delete the items at position I from the list and then add a zero to the end. It is important to note, that the index needs to be decremented by one in case a 0
is found to account for double 0
. The number of steps needs to always be increased.
from typing import List, Optional
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
pos = 0
steps = 0
while steps < len(nums):
if nums[pos] == 0:
del nums[pos]
nums.append(0)
pos -= 1
pos += 1
steps += 1
if __name__ == '__main__':
s = Solution().moveZeroes
l = [0,1,0,3,12]
print(s(l), [1,3,12,0,0])
l = [0]
print(s(l), [0])
l = [0,0,1]
print(s(l), [1,0,0])