Given anarray with n objects colored red, white or blue, sort them so thatobjects of the same color are adjacent, with the colors in the order red, whiteand 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.
思路:
因为只有3种颜色,所以借助map结构,统计每种颜色的数量;
清空原来vector里面的内容;
按照map结构中统计的数据重新往vector里面加值。
class Solution {
public:
void sortColors(vector<int>& nums) {
map<int, int> counts;
counts.insert({0, 0});
counts.insert({1, 0});
counts.insert({2, 0});
for(auto item: nums)
{
switch(item)
{
case 0:
++counts[0];
break;
case 1:
++counts[1];
break;
case 2:
++counts[2];
break;
}
}
nums.clear();
for(auto iter = counts.begin(); iter != counts.end(); ++ iter)
{
while(iter->second--)
nums.push_back(iter->first);
}
return;
}
};