Move Zeros
Two pointers
Problem
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.
Solution
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
i = 0
j = 0 #pointer position for putting the non-zeroes
while i < len(nums):
if nums[i] != 0:
t = nums[j]
nums[j] = nums[i]
nums[i] = t
j+=1
i+=1
Last updated
Was this helpful?