前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Sort Colors

Leetcode: Sort Colors

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 15:10:01
3110
发布2019-01-22 15:10:01
举报

题目: 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.

思路分析: 题目出了这样的提示: 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?

按照提示two-pass算法代码如下,这个比较简单。 C++参考代码:

代码语言:javascript
复制
class Solution
{
public:
    void sortColors(int A[], int n)
    {
        int count[3] = {0};
        for (int i = 0; i < n; i++)
        {
            if (0 == A[i]) count[0] += 1;
            else if (1 == A[i]) count[1] += 1;
            else if (2 == A[i]) count[2] += 1;
        }
        int x = count[0] + count[1];
        int y = x + count[2];
        for (int i = 0; i < n; i++)
        {
            if (i < count[0]) A[i] = 0;
            else if (i < x) A[i] = 1;
            else if (i < y) A[i] = 2;
        }
    }
};

那什么是所谓的one-pass算法呢?

我们可以定义两个指针:一个指针left指向当前应该插入0的位置,一个指针right指向当前应该插入2的位置,再利用一个指针current进行循环遍历。遇到0的时候就插入left的位置,left前进一位,遇到2的时候就插入right的位置,right后退一位,遇到1的时候,current前进一位。

C++参考代码:

代码语言:javascript
复制
class Solution
{
public:
    void sortColors(int A[], int n)
    {
        int left = 0;
        int right = n - 1;
        int current = 0;
        //注意这里是<=不是<
        while (current <= right)
        {
            if (0 == A[current])
            {
                swap(A[current], A[left]);
                ++left;
                //处理left可能大于current的情况
                current = left > current ? left : current;
            }
            else if (2 == A[current])
            {
                swap(A[current], A[right]);
                --right;
            }
            else
            {
                ++current;
            }
        }
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年04月10日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档