75. Sort Colors
Given an array nums
with n
objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0
, 1
, and 2
to represent the color red, white, and blue, respectively.
Note: Don't increment current pointer if find Blue or the color that goes to the right. Dutch National Flag.
def sortColors(nums):
"""
Do not return anything, modify nums in-place instead.
"""
red_next = 0
blue_next = len(nums) -1
def swap(i, j):
nums[i], nums[j] = nums[j], nums[i]
cur = 0
while cur <= blue_next:
if nums[cur] == 0:
swap(cur, red_next)
red_next += 1
cur += 1
elif nums[cur] == 2:
swap(cur, blue_next)
blue_next -= 1
else:
cur += 1
Comments
Post a Comment