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?
Test instructions: Just in the array a[], reorder the 0,1,2.
Idea: counting sort or three pointers to do, a pointer to the location of red, a pointer to blue position, then can be placed in turn, the middle of the non-processing is all white
Class Solution {public: void sortcolors (int a[], int n) { if (A = = NULL | | n < 2) return; int NUM0 = 0, num1 = 0, num2 = 0; for (int i = 0; i < n; i++) { if (a[i] = = 0) num0++; else if (a[i] = = 1) num1++; else num2++; } int i = 0; while (num0--) a[i++] = 0; while (num1--) a[i++] = 1; while (num2--) a[i++] = 2; }};
Class Solution {public: void sortcolors (int a[], int n) { if (A = = NULL | | n < 2) return; int red = 0, blue = n-1; for (int i = red; I <= blue; i++) { if (a[i] = = 0) swap (a[red++], a[i]); else if (a[i] = = 2) swap (a[blue--], a[i--]);}} ;
Leetcode Sort Colors