Photo by Tai Bui on Unsplash |
Question:
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.
Topics: Array , Two Pointers
Link : https://leetcode.com/problems/move-zeroes/description/
Solution:
Pointer
i
: Keeps track of the position where the next non-zero element should go.-
Pointer
j
: Iterates over the entire array.
Plan:
-
Start with
i = 0
andj = 0
. -
Traverse through the array:
-
Whenever
nums[j]
is non-zero, move it to positioni
, and then incrementi
. -
Continue until you've gone through the entire array.
-
-
After this loop, all non-zero elements will be in their correct positions, and
i
will indicate where the0
s should start.
Solution Code:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = 0
for j in range(len(nums)):
if nums[j] != 0:
nums[i], nums[j]= nums[j] ,nums[i]
i = i + 1
return nums
Put Your Thought or Query Here