75. Sort Colors
https://leetcode.com/problems/sort-colors/
Make two pointer for two bounds
zeroBound 从左往右第一个不是0的位置,前面经过swap都是0
twoBound从右往左第一个不是2的位置,后面经过swap都是2
唯一需要注意的是这里的curr在进行zeroBound变换时,需要increment
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zeroBound = 0
twoBound = len(nums)-1
curr = 0
while curr <= twoBound:
if nums[curr] == 0:
nums[curr],nums[zeroBound] = nums[zeroBound],nums[curr]
zeroBound+=1
curr+=1
elif nums[curr] == 2:
nums[curr],nums[twoBound] = nums[twoBound],nums[curr]
twoBound-=1
else:
curr+=1
Last updated
Was this helpful?