The color class is given an array of red, white, blue, and length n, and the array elements are categorized so that the elements of the same color are adjacent and sorted in the order of red, white, and blue.
We can use integers 0,1 and 2 to represent red, white, and blue, respectively.
Sample Example
Note
You cannot use the sort function in the code base to solve this problem
Description
A fairly straightforward solution is to use counting sorting to scan the algorithm 2 times.
First, the iterated algebraic group calculates the number of occurrences of 0,1,2, then overwrites the array with the number of occurrences of 0,1,2.
Can you think of an algorithm that only uses the constant-level extra space complexity and scans the array only once?
The code is a messy, rarely written note.
The idea is to swap 0 to the left and 2 to the right.
1 classSolution {2 //Total time: 14896 Ms3 4 /**5 * @paramnums:a List of integers which is 0, 1 or 26 * @return: Nothing7 */8 Public voidSortcolors (int[] nums) {9 intLow = 0;Ten intHigh = Nums.length-1; One //first find the leftmost non 0 and right non 2 A while(Nums[low] = = 0 && Low < high) low++; - while(Nums[high] = = 2 && low < high) high--; - the while(Nums[low] = = 2 | | nums[high] = = 0 && Low <High ) { - //if the leftmost 0 is 2 or the rightmost 2 is 0, change it to the right or left - if(Nums[low] = = 2) { - if(Nums[high] = = 0) { +nums[low++] = 0; -nums[high--] = 2; +}Else { Anums[high--] = 2; atNums[low] = 1; - } -}Else { - if(Nums[high] = = 0) { -nums[low++] = 0; -Nums[high] = 1; in } - } to //find the leftmost non 0 and right non 2 + while(Nums[low] = = 0 && Low < high) low++; - while(Nums[high] = = 2 && low < high) high--; the } * $ for(intI=low+1;i) {Panax Notoginseng //at this time the leftmost non 0 and the right 2 are 1, with I find 0 or 2, swapped to the left or right side - if(Nums[i] = = 0) { thenums[low++] = 0; +Nums[i] = 1; A}Else { the if(Nums[i] = = 2) { +nums[high--] = 2; -Nums[i] = 1; $ } $ } - - //find the leftmost non 0 and right non 2 the while(Nums[low] = = 0 && Low < high) low++; - while(Nums[high] = = 2 && low < high) high--;Wuyi the while(Nums[low] = = 2 | | nums[high] = = 0 && Low <High ) { - //if the leftmost 0 is 2 or the rightmost 2 is 0, change it to the right or left Wu if(Nums[low] = = 2) { - if(Nums[high] = = 0) { Aboutnums[low++] = 0; $nums[high--] = 2; -}Else { -nums[high--] = 2; -Nums[low] = 1; A } +}Else { the if(Nums[high] = = 0) { -nums[low++] = 0; $Nums[high] = 1; the } the } the //find the leftmost non 0 and right non 2 the while(Nums[low] = = 0 && Low < high) low++; - while(Nums[high] = = 2 && low < high) high--; in } the //if the low>=i at this time, obviously to reset I the if(I <= low) i = low+1; About } the //when the above loop ends, the classification is completed, only one nums is traversed, and the secondary space is constant the } the}View Code
Color Classification (Lintcode)