Claim
Only to sort an array of three elements 0,1,2
Thinking
Method 1: traverse the array, the auxiliary array holds the number of elements of three, and then write (traversed twice)
Method 2: an analog three-way fast row, traversing again been sequenced
achieve
method 1
1 void sortColors(vector<int>& nums){ 2 int count[3] = {0}; 3 for( int i = 0 ; i < nums.size() ; i ++ ){ 4 assert( num[i] >= 0 && nums[i] <= 2 ); 5 count[nums[i]] ++; 6 } 7 8 int index = 0; 9 for( int i = 0 ; i < count[0] ; i ++ ){ 10 nums[index++] = 0; 11 for( int i = 0 ; i < count[1] ; i ++ ){ 12 nums[index++] = 1; 13 for( int i = 0 ; i < count[2] ; i ++ ){ 14 nums[index++] = 2; 15 } 16 }
Method 2
1 void sortColors1(vector<int>& nums){ 2 int zero = -1; 3 int two = nums.size(); 4 for( int i = 0 ; i < two ; ){ 5 if( nums[i] == 1 ) 6 i ++; 7 else if( nums[i] == 2 ){ 8 two --; 9 swap( nums[i] , nums[two] ); 10 }else{ 11 assert( nums[i] == 0 ); 12 zero ++; 13 swap( nums[zero] , nums[i] ); 14 i ++; 15 } 16 } 17 }
Similar problems
215 Kth Largest Element in an Array