Dutch national flag problem

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.

It's actually Dutch national flag problem.

[, i): 0 
[i, j]: 1
(k, ...]: 2
Once j meets k, the sorting is complete
class Solution {
public:
    void sortColors(vector<int>& nums) {
        int i=0, j=i, k=nums.size()-1;
        while(j<=k)
        {
            if(nums[j]==0) swap(nums[i++], nums[j++]);
            else if(nums[j]==1) j++;
           //还不知道j交换之后是什么元素,因此未移动j
            else swap(nums[j], nums[k--]);
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,172评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,495评论 0 23
  • 我穿着红裤衩来到了新手村,绿油油的草坪上几只红毛尖喙的公鸡正在悠闲地觅食,我赤手空拳打死了一只公鸡,这时我得到了一...
    大漠雄鹰直击长空阅读 1,841评论 0 4
  • 2018.4.24 一、肯定法 1、在玩具店逛了快半个小时,哪个都想要,(一周内已经买了两把玩具枪了)最后什么都没...
    文娜_阅读 1,283评论 0 0
  • 给我首页的小宝贝们,抱紧,不要再伤心啦。 不会谈恋爱就不谈, 交不到朋友就不交, 讲不通道理就屏蔽, 看不顺眼就删...
    akoo阅读 1,652评论 0 0

友情链接更多精彩内容