Problem
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.
Algorithm
Use two pointers, exchange each first non-zero number after zeros.
Code
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
num_len = len(nums)
index1, index2 = 0, 0
while index2 < num_len:
while index1 < num_len and nums[index1]:
index1 += 1
index2 = index1 + 1
while index2 < num_len and not nums[index2]:
index2 += 1
if index2 < num_len:
buffer = nums[index1]
nums[index1] = nums[index2]
nums[index2] = buffer