75. Sort Colors/颜色分类

Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

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 a one-pass algorithm using only constant space?

AC代码

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int l = 0, r = nums.size() - 1;
        for (int i = 0; i <= r; ++i) {
            while (nums[i] != 1) {
                if (i > r || i < l) break;
                else if (nums[i] == 0) swap(nums[i], nums[l++]);
                else if (nums[i] == 2) swap(nums[i], nums[r--]);
            }
        }
    }
};

他人代码

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int red = 0, blue = nums.size() - 1;
        for (int i = 0; i <= blue; ++i) {
            if (nums[i] == 0) swap(nums[i], nums[red++]);
            else if (nums[i] == 2) swap(nums[i--], nums[blue--]);          
        }
    }
};

总结

一次遍历还要O(1)空间复杂度,用双指针,自己写的稍有复杂,别人写的更简单易懂。照抄自:https://www.cnblogs.com/grandyang/p/4341243.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,436评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,850评论 0 23
  • 《流浪猫》影评 写在前面 这是我的人生第三篇影评,形式上复制了上一篇的模板,文字上依然潇洒帅气,目标上为了...
    沈剑坤阅读 582评论 0 2
  • 文||十一 图||网络 本以为随着凶手陈世峰在日本获刑而后放弃上诉,江歌案可以尘埃落定了。 万万没想到,在庭审后...
    时糖Tsugar911阅读 740评论 1 2
  • 明日工作计划 10:15分到店 13:30开始收资源 19:00完成任务 维护客户
    梧桐16阅读 170评论 0 0