Topic:
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?
Tag:array, the other pointers, sort experience: The problem is to see other people's practice before you know. This question can be said to be quicksort inside of that partition of another variant: Partition into many paragraphs. The original partition is only divided into two segments, X <= pivot and x > pivot. And this question is asked to be divided into three paragraphs, assuming we are in some intermediate process, we are going to check the elements on A[p], at this point A should be like this: [0,0,.. 0,1,1,.. 1,2,2,.. 2, p, unsorted part] I J p-1 we need to have two pointers, one pointer to the last index of the 0 part, the last index of the 1 part, and the last of the 2 parts we can get for free, that is, p-1. Then we will see A[p], if A[P] is 2, do nothing to continue to maintain the original cycle invariant, if a[p] is 1, then 1 parts of the size will be larger one, so j = j + 1, and then put A[j] 1, the a[p] is placed 2; Similarly, if it is a[p] = 0, then 0 parts to be larger, I = i+1, a[i] = 0, 1 parts followed by the deferred, j = j+1, a[j] = 1, and finally a[p]=2. In the original partition algorithm should be the pointer to become larger after the "exchange" operation, and this problem can be directly assigned to 0, 1, or 2, because we know the value to be assigned. For example partition: [0, 6, 5, p, .... pivot=9] I when checking to P-bit, if p<=pivot, then i = i +1, a[i] <-> a[p], (i.e. A[i] and a[p]). But this problem, we know if it is 0 part of i = i + 1, then a[i] must be to become 0, 1 part of the expansion, j = j+1, A[j] must be to become 1, so you can directly assign values, instead of swapping. Ah ah, I said too wordy, completely to make a note for themselves, we do not shoot me ah ...
1 classSolution {2 Public:3 voidSortcolors (intA[],intN) {4 inti =-1;5 intj =-1;6 for(intp =0; P < n; p++) {7 if(A[p] = =2) {8 //Do nothing but moving the index of K9}Else if(A[p] = =1) {Ten // OneA[P] =2; AA[++J] =1; -}Else { -A[P] =2; theA[++J] =1; -A[++i] =0; - } - } + } -};
[Leetcode] Sort Colors (c + +)