【LeetCode】075. Sort Colors


Given an array withnobjects 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?

解1 计数排序

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& v) {
 4         vector<int> count(3, 0);
 5         
 6         for (int i = 0; i < v.size(); ++i) {
 7             if (v[i] == 0) {
 8                 ++count[0];
 9             } else if (v[i] == 1) {
10                 ++count[1];
11             } else {
12                 ++count[2];
13             }
14         }
15         
16         int it = 0;
17         for (int i = 0; i < 3; ++i) {
18             for (int j = 0; j < count[i]; ++j) {
19                 v[it++] = i;
20             }
21         }
22     }
23 };

解2 双指针思想的延伸

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& v) {
 4         int low = 0, mid = 0, high = v.size() - 1;
 5         while (mid <= high) {
 6             if (v[mid] == 0) {
 7                 swap(v[mid], v[low]);
 8                 ++low;
 9                 ++mid;
10             } else if (v[mid] == 2) {
11                 swap(v[mid], v[high]);
12                 --high;
13             } else {
14                 ++mid;
15             }
16         }
17     }
18 };

解3 比较有技巧

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& v) {
 4         int n0 = -1, n1 = -1, n2 = -1;
 5         
 6         for (int i = 0; i < v.size(); ++i) {
 7             if (v[i] == 0) {
 8                 v[++n2] = 2;
 9                 v[++n1] = 1;
10                 v[++n0] = 0;
11             } else if (v[i] == 1) {
12                 v[++n2] = 2;
13                 v[++n1] = 1;
14             } else {
15                 v[++n2] = 2;
16             }
17         }
18     }
19 };

优质内容筛选与推荐>>
1、ios 实现字符串的MD5加密方法
2、canvas绘制小人开口和闭口
3、阿里云 RDS for MySQL 物理备份文件恢复到自建数据库
4、高质量C++/C编程指南--第5章常量
5、BugFree在Windows平台上面的安装步骤


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn