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.
0 1 2
Count-sort like, but in one pass
Pointers start from beginning
Zero stands for the end of 0s
One stands for the end of 1s
A third pointer iterate through the array, when found a 1, change the current number to 2 and change one to 1 and move one To Next
When found a 0, the change of the current number to 2, change one to 1, move one to next and then change from zero to 0, move Zero to next (order matters, when one was at the same position as zero, we want this position to being 0 at T to 1 First,then 0)
Public voidSortcolors (int[] nums) { if(Nums = =NULL|| Nums.length = = 0)return; intZero = 0; intone = 0; for(inti = 0; i < nums.length; i++){ if(Nums[i] = = 0) {Nums[i]= 2; Nums[one+ +] = 1; Nums[zero+ +] = 0; } Else if(Nums[i] = = 1) {Nums[i]= 2; Nums[one+ +] = 1; } } }
Now we add one restriction: What's in the array are not integers, is a object, so we could only use swap
if (Nums[cur] = = 1) { cur+ +;} Else if (Nums[cur] = = 0) { swap (cur, zero); Zero+ +; Cur+ +;} Else { swap (cur, both); double--;}
[Leetcode] Sort Colors