[leetcode 75] Sort Colors-----------只有三种颜色的排序

Question:

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.

分析:

题目意思是,0---红色,1---白色,2----蓝色。不能用模板中自带的sort方法,使得数组中的颜色按照红白蓝色排序。

只有三种颜色,所以只要依次将0排在前,1排在前即可,不用刻意排2,已经在后面了;

实现方法,设置两个指针left,right;初始化数组的头和尾。

1、依次判断left指向的数据是不是0,是left++,不是,交换从后面数第一个0,然后--right和++left;

2、重置right为原数组的尾,left接上面的值,从left开始判断,left指向的值是不是1,是++left,不是则和后面数第一个1交换。


代码如下:

<span style="font-size:14px;">class Solution {
public:
    void sortColors(vector<int>& nums) {
        if(nums.size() <= 1){
            return ;
        }
        int left = 0;
        int right = nums.size()-1;
        vector<int>::iterator it;
        
        for(int i = 0; i < 2; ++i){
            it = find(nums.begin()+left,nums.end(),i);
            if(it == nums.end())
                continue;
            while(left < right){
                if(nums[left] <= i){
                    ++left;
                }
                else{
                    int t = nums[left];
                    while(nums[right] != i && right > left)
                        --right;
                    if(left == right)
                        continue;
                    else{
                        nums[left] = i;
                        nums[right] = t;
                        ++left;
                        --right;
                    }
                }
            }
            right = nums.size()-1;
        }
        
    }
};</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值