Sort Colors
Question
None
Example 1
Input: [2,1,0,2,2,1]
Output: [0,1,1,2,2,2]
Solution
- ▭
- ▯
all//Sort Colors.py
def sortColors(nums):
lo, hi = 0, len(nums) - 1
mid = 0
while mid <= hi:
if nums[mid] == 0:
nums[lo], nums[mid] = nums[mid], nums[lo]
lo += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[hi] = nums[hi], nums[mid]
hi -= 1
return nums
nums = [2,0,2,1,1,0]
print(sortColors(nums)) # [0, 0, 1, 1, 2, 2]
all//Sort Colors.py
def sortColors(nums):
lo, hi = 0, len(nums) - 1
mid = 0
while mid <= hi:
if nums[mid] == 0:
nums[lo], nums[mid] = nums[mid], nums[lo]
lo += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[hi] = nums[hi], nums[mid]
hi -= 1
return nums
nums = [2,0,2,1,1,0]
print(sortColors(nums)) # [0, 0, 1, 1, 2, 2]