283. 移动零
image-20201119103934250
思路
双指针
左指针指向左边已经排好序的尾部,右指针指向当前数字,右指针如果指向的数字不为0,则交换左右指针。 注意:当非0数字在前面时,左右指针会相等。
class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ if len(nums) == 0: return i = j = 0 while j < len(nums): if nums[j] != 0: # 如果i和j不等则替换 if i != j: nums[i], nums[j] = nums[j], nums[i] i += 1 j += 1
image-20201119104255205