Given an array with n objects colored red, white or blue, sort them so, objects of the same color is Adjacen T, with the colors in the order red, white and blue.
Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You is not a suppose to use the library's sort function for this problem.
Click to show follow up.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0 ' s, 1 ' s, and 2 ' s, then overwrite array with total number of 0 ' s, then 1 ' s and Followed by 2 ' s.
Could you come up with a one-pass algorithm using only constant space?
The solution of a very intuitive, as long as the scan once nums, the number of 0,1,2 in the inside record down on the line.
OJ Request One-pass, refer to the solution of Xi brush. Suppose the current situation is as follows:
0......0 1......1 x1 x2 .... XM 2.....2 | | | Left cur right 1. If X1 = = 1, cur ++2. If X1 = = 0, x1 and Nums[left] Swap, left + +, cur ++3. If X1 = = 2, x1 and nums[right] swap, right--。 Note that the third case cannot be cur++, and XM may be 2 or 0. But don't worry about it after swapping with Case2 X1 and Nums[left]. Because at the beginning cur = left, if the cur is ahead of it, then the case1 must have happened, then nums[left] must be equal to 1. This idea only applies to the case of 3 colors, in other words, if the color is more than three, then it must be solved with two-pass.
1 classsolution (object):2 defsortcolors (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:void does not return anything, modify Nums in-place instead.6 """7n =Len (nums)8left =09right = N-1Teni =0 One A whileI <=Right : - ifNums[i] = =0: -Nums[i], nums[left] =Nums[left], Nums[i] theLeft + = 1 -i + = 1 - elifNums[i] = = 2: -Nums[i], nums[right] =Nums[right], Nums[i] +Right-= 1 - Else: +i + = 1
Leetcode 75. Sort Colors