把仅含0,1,2的数组排序,要求只遍历一遍
思路:三指针
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
l = 0
r = len(nums)-1
mid = 0
while mid<=r:
if nums[mid] == 0:
nums[mid],nums[l] = nums[l],nums[mid]
l+=1
mid+=1
elif nums[mid]==1:
mid+=1
else:
nums[r],nums[mid]=nums[mid],nums[r]
r-=1
return nums