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.
Constraints:
- 1 <= nums.length <= 104
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
'''
move 0 to the end: delete 0, and append 0
need to remember original index number (of pointer)
end if checked original array's end position
'''
point_idx = 0
# check numbers for original num's length times
for _ in range(len(nums)):
if nums[point_idx] == 0:
# move 0 to the end
del nums[point_idx]
nums.append(0)
# update point_idx
pass
else:
# update point_idx
point_idx += 1
➡ Solved✅
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
anchor = 0
for explorer in range(len(nums)):
if nums[explorer] != 0:
nums[anchor], nums[explorer] = nums[explorer], nums[anchor]
anchor += 1