LeetCode 75
因为只有三种颜色,并且需要inplace来做修改,我们直到排序之后一定是【x个0,y个1,z个2】这样的结果,我们可以遍历数组,把等于0的交换到最前面去,把等于2的交换到最后面去。
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
r0 = 0 #right position of 0 colors
l = 0
h = len(nums) - 1
while (l <= h):
if nums[l] == 0:
if l != r0:
temp = nums[r0]
nums[r0] = 0
nums[l] = temp
r0 +=1
l +=1
elif nums[l] == 2:
temp = nums[h]
nums[h] = 2
nums[l] = temp
h -=1
else:
l+=1
return nums