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.
解决方法是计数排序,代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int colors[3]={0};
for(int i=0;i<nums.size();i++){
colors[nums[i]]++;
}
for(int i=1;i<3;i++){
colors[i]+=colors[i-1];
}
vector<int> temp=nums;
for(int i=nums.size()-1;i>=0;i--){
nums[colors[temp[i]]-1]=temp[i];
colors[temp[i]]--;
}
return;
}
};

本文介绍了一种不使用标准库排序函数的颜色排序算法。该算法适用于含有红、白、蓝三种颜色的数组,通过计数每种颜色的数量并重新排列,实现相同颜色相邻且按红、白、蓝顺序排列的目标。
172

被折叠的 条评论
为什么被折叠?



