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 aren't suppose to use the library's sort function for this problem
==========
There are three colors of objects, the colors are red,waite,blue, respectively, using an array of 0,1,2 to represent.
The requirements are: sort the objects by color red,waite,blue.
=======
Ideas:
The idea of using a quick sort:
Begin: Point to the location that will be sorted to red (0)
End: Point to where you want to sort blue (2)
Curr: Traverse Pointer,
If the current element is 0, then and begin position swap, notify begin++,curr++
If the current element is 1,curr++
If the current element is 2, then the end position is swap, but the curr element cannot be incremented, end--
====
Code
classSolution { Public: voidSortcolors (vector<int>&nums) { intn =nums.size (); intCurr,begin,end; Curr= BEGIN =0; End= N1; while(curr<=end) { if(nums[curr]==0) {Swap (Nums[begin++],nums[curr++]); }Else if(nums[curr]==1) {Curr++; }Else if(nums[curr]==2) {swap (Nums[end],nums[curr]); End--; } } }};
The. Sort Colors