ByteByteGo: Shift Zeros to the End
β’ 89 words β’ 1 min β’ updated
ByteByteGo: Shift Zeros to the End:
python
from typing import List
def shift_zeros_to_the_end(nums: List[int]) -> None:
j = None
for i, num in enumerate(nums):
if num != 0:
if j is not None:
assert j < i
nums[i], nums[j] = nums[j], nums[i]
j += 1
else:
if j is None:
j = iSimplified version:
python
from typing import List
def shift_zeros_to_the_end(nums: List[int]) -> None:
j = 0
for i, num in enumerate(nums):
if num != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1