Method One: OK, the ugly way, but write it yourself ... Draw on the thought of the Fast platoon partition
1 classSolution {2 Public:3 voidSortcolors (vector<int>&nums) {4 if(nums.size () = =0)return;5vector<int> Start (3, -1);6start[nums[0]] =0;7 for(inti =1; I < nums.size (); ++i) {8 if(Nums[i] = = Nums[i-1])Continue;9 Else {Ten if(Start[nums[i]] = =-1) { One if(Nums[i] = =2) { Astart[2] = i;Continue; - } - Else if(Nums[i] = =1) { the if(start[2] == -1) { -start[1] = i;Continue; - } - Else { +start[1] = start[2]; -Nums[i] =2; +nums[start[1]] =1; A++start[2]; at } - } - Else { - //cannot appear start[1] = start[2] = 1, the first element has been determined by a - //here start[1] and start[2] at least one is not-1 - if(start[2] != -1) { innums[start[2]] =0; -start[0] = start[2]; to++start[2]; +Nums[i] =2; - if(start[1] != -1) { thenums[start[1]] =0; *nums[start[0]] =1; $start[0] = start[1];Panax Notoginseng++start[1]; - } the Else Continue; + } A Else { thenums[start[1]] =0; +Nums[i] =1; -start[0] = start[1]; $++start[1]; $ } - } - } the Else { - if(Nums[i] = = Nums[i-1])Continue;Wuyi Else { the if(Nums[i] = =0) { - if(start[2] == -1) { WuNums[i] =1; -nums[start[1]] =0; About++start[1]; $ } - Else { -nums[start[2]] =0; -Nums[i] =2; A++start[2]; + if(start[1] != -1) { thenums[start[1]] =0; -nums[start[2] -1] =1; $++start[1]; the } the } the } the Else { - //Nums[i] = = 1, cannot be 2, and the previous one must be 2 inNums[i] =2; thenums[start[2]] =1; the++start[2]; About } the } the } the } + } - } the};
Method Two: Two pointers, two to the middle walk, method one just start from the end, resulting in the program is too complex
1 classSolution {2 Public:3 voidSortcolors (vector<int>&A) {4 intRed =0, blue = A.size ()-1;5 for(inti =0; I < Blue +1; ) {6 if(A[i] = =0) Swap (a[i + +), a[red + +]);7 Else if(A[i] = =2) Swap (a[i + +), A[blue--]);8 Else++i;9 }Ten } One};
Method Three:
075. Sort Colors