Sort Colors

最后更新于:2022-04-01 22:58:05

**一. 题目描述** 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. Follow up:  A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s,  then 1’s and followed by 2’s. Could you come up with an one-pass algorithm using only constant space? **二. 题目分析** 题目一开始说到一组对象,包含红白蓝三种颜色,然后要对他们进行排序,说白了就是对一个只含有`0, 1, 2`三个数字的数组从小到大排序。 题目要求:come up with an one-pass algorithm using only constant space,因此只能扫描一次。这里采取的方法是,统计`0, 1, 2`三个数字分别出现的次数,再将数组nums重新构建为从0到2排列的数组,这种方法没有使用数组元素间的交换,只需扫描一次nums。 **三. 示例代码** ~~~ #include #include using namespace std; class Solution { public: void sortColors(vector& nums) { int SIZE = nums.size(); int count[3] = {0, 0, 0}; for (int i = 0; i < SIZE; ++i) ++count[nums[i]]; for (int i = 0, index = 0; i < 3; ++i) for (int j = 0; j < count[i]; ++j) nums[index++] = i; } }; ~~~ 一个测试结果: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-05_568bb5f18a45c.jpg) **四. 小结** 本题的解法还是挺多的,可多参考网上的其他解法。
';