title :
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?
Code: OJ tested via runtime:47 MS
1 classSolution:2 #@param a a list of integers3 #@return Nothing, sort in place4 defsortcolors (Self, A):5 #None Case6 ifA isNone:7 returnNone8 #pointers:p0 for red and p2 for blue9P0 =0TenP2 = Len (A)-1 Onei =0 A whileI <=P2: - ifA[i] = =0: -A[I],A[P0] =A[p0],a[i] thei + = 1 -P0 + = 1 - elifA[i] = = 1 : -i + = 1 + Else : -A[I],A[P2] =A[p2],a[i] +P2-= 1
Ideas :
The requirement of this problem is similar to the requirements of many array problems, how to traverse the array to complete the task.
is to put two pointers in each of the tail.
Because there are three types of elements, it is necessary to guard the two pointers on each tail.
Many of the array topics are used to exchange the value of the elements of the technique, traverse it once.
Leetcode "Sort Colors" Python implementation