两个易错点:
1.什么时候p才可以+1?当前位置为1
2.nums[p]==2需要提前:换过来的数字可能为0或1,而nums[p]==0换过来的数字只可能是1
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
p1, p2, p = 0, len(nums)-1, 0
while(p<=p2):
while p<p2 and nums[p]==2:
nums[p], nums[p2] = nums[p2], nums[p]
p2 -= 1
while p1<p and nums[p]==0:
nums[p], nums[p1] = nums[p1], nums[p]
p1 += 1
p += 1
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
p1, p2, p = 0, len(nums)-1, 0
while(p<=p2):
if nums[p]==2:
nums[p], nums[p2] = nums[p2], nums[p]
p2 -= 1
p -= 1
elif nums[p]==0:
nums[p], nums[p1] = nums[p1], nums[p]
p1 += 1
p += 1