Topic:
Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He 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.
Thinking Analysis:
The topic is a hint like this:
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?
Follow the prompts Two-pass algorithm code as follows, this is relatively simple.
C + + Reference code:
class solution{ Public:voidSortcolors (intA[],intN) {int Count[3] = {0}; for(inti =0; I < n; i++) {if(0= = A[i])Count[0] +=1;Else if(1= = A[i])Count[1] +=1;Else if(2= = A[i])Count[2] +=1; }intx =Count[0] +Count[1];inty = x +Count[2]; for(inti =0; I < n; i++) {if(I <Count[0]) A[i] =0;Else if(I < x) A[i] =1;Else if(I < Y) A[i] =2; } }};
What is the so-called One-pass algorithm?
We can define two pointers: A pointer to the left pointing to the position where the current should be inserted 0, a pointer to the position where the current should be inserted 2, and a pointer to loop through. Encountered 0 when the left position is inserted, left forward one, encountered 2 when the right position is inserted, back one, when encountering 1, current forward one.
C + + Reference code:
Class solution{ Public:void sortcolors(intA[],intN) {intleft =0;intright = N-1;intCurrent =0;//Note This is <= not < while(Current <= right) {if(0= = A[current]) {swap (a[current], a[left]); ++left;//Handle a situation where left may be greater than currentCurrent = left > current? Left:current; }Else if(2= = A[current]) {swap (a[current], a[right]); --right; }Else{++current; } } }};
Leetcode:sort Colors