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.
Note:
You is not a suppose to use the library's sort function for this problem.
In fact, the problem is the sorting issue, the same elements are queued together, different elements need to be prioritized before and after the priority order.
Thinking Analysis:
The most intuitive solution to the problem of the follow up has been given, but need to traverse two times, other similar methods also need to traverse over, such as the method of exchanging elements, the first time all 0 to the front, the second time all 1 then to the first pass the last position, 2 automatically changed to the last side. Then see if there is a way to traverse it all over again. Occasionally see there is such a solution, feel quite ingenious, but did not give too much explanation, carefully analyzed several times code, detailed introduction under:
The core idea is to record the index of the last 0,1,2 with three cursors, and when inserting 0 o'clock, all indexes move back one position at a time (copy one position later), similarly, when inserting 1 o'clock, 2 copying a position back, inserting 2 o'clock, updating the index of 2 directly, and inserting the operation.
The code is as follows:
<span style= "FONT-SIZE:14PX;" >void sortcolors (vector<int>& nums) {
int ilastzero = -1//three indexes ...
int ilastone =-1;
int ilasttwo =-1;
for (size_t i = 0; i < nums.size (); ++i)
{
if (0 = = nums[i])//insert 0
{
Nums[++ilasttwo] = 2;//index of Backwards a 2
nums[++ilastone] = 1;
Nums[++ilastzero] = 0;
}
else if (1 = = Nums[i])
{
Nums[++ilasttwo] = 2;
Nums[++ilastone] = 1;
}
else if (2 = = Nums[i])
{
Nums[++ilasttwo] = 2;
}
else
{
//for other cases.
}
}
} </span></span>
Look at a specific example:
Given an array: nums: [1,2,0,1,0], the following is the result of the processing after each iteration.