美文网首页Algorithm
Dutch national flag problem

Dutch national flag problem

作者: 世界上的一道风 | 来源:发表于2019-07-18 09:01 被阅读0次

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--]);
        }
    }
};

相关文章

网友评论

    本文标题:Dutch national flag problem

    本文链接:https://www.haomeiwen.com/subject/rycklctx.html