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.
Solution
class Solution {
public:
void sortColors(vector<int>& nums)
{
//桶排序
int len = nums.size();
int Count[3] = {};
for(int i=0;i<len;i++)
Count[nums[i]]++;
for(int i=0;i<Count[0];i++)
nums[i] = 0;
for(int i=Count[0];i<Count[0]+Count[1];i++)
nums[i] = 1;
for(int i=Count[0]+Count[1];i<len;i++)
nums[i] = 2;
}
};

本文介绍了一种不使用标准库排序功能的特定颜色数组排序算法。该算法通过桶排序实现,将红色、白色和蓝色(分别用0、1、2表示)相邻排列,并保持颜色顺序。文中提供了一个C++实现示例。
3111

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



