题目:
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
思路:
分别计算元素0 , 1 , 2 的个数,然后对原数组重新赋值、
程序:
class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.empty())
return;
vector<int> count(3, 0);
vector<int>::iterator iter = nums.begin();
for (; iter != nums.end(); iter++)
{
if (*iter == 0)
count[0]++;
else if (*iter == 1)
count[1]++;
else if (*iter == 2)
count[2]++;
}
int i = 0;
while (i < count[0])
nums[i++] = 0;
while (i < (count[0] + count[1]))
nums[i++] = 1;
while (i < (count[0] + count[1] + count[2]))
nums[i++] = 2;
return;
}
};