Sort Colors
Question
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Example
Given [1, 0, 1, 2]
, return [0, 1, 1, 2]
.
Analysis
时间,空间复杂度要求
Thoughts
如果几下各自的数目再产生一个新的array很简单
one-pass的方法 用两个pointer,分别记red和blue的数量,再遍历的途中swap
注意
- 到了blue的分界就可以停止了
- swap了一个blue之后不能直接往后,还要再check swap过来的value, 对于red的swap则不用,因为之前已经访问过了
Solution
class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
# write your code here
numRed = 0
numBlue = 0
length = len(nums)
index = 0
#stop when reach blue
while index <= length - 1 - numBlue:
if nums[index] == 0:
nums = self.swap(nums, numRed, index)
numRed += 1
index += 1
elif nums[index] == 1:
index += 1
elif nums[index] == 2:
nums = self.swap(nums, length - 1 - numBlue, index)
numBlue += 1
#index 不加1, 要判断swap回来的value
def swap(self, nums, i, j):
tmp = nums[j]
nums[j] = nums[i]
nums[i] = tmp
return nums