LeetCode 75. Sort Colors (三路快排)

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.

题意:red ----0,white----1,blue----2,数组nums只会含有0,1,2三个值,并排序

1.简单的直接调用排序函数,这里注意一下vector排序函数的传递参数为首尾两个迭代器,默认升序。还可以自定义排序方式

class Solution {
public:
    void sortColors(vector<int>& nums) {
        sort(nums.begin(),nums.end());
    }
};


2.观察该数组我们发现,分别统一0,1,2三个元素的个数再来赋值,统计排序。

class Solution {
public:
    void sortColors(vector<int>& nums) {
        //1.sort(nums.begin(),nums.end());
        int count[3]={0};
        for(int i:nums)
        {
            count[i]++;
        }
        int index =0;
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<count[i];j++)
            {
                nums[index++] = i;
            }
        }
    }
};

3.三路快排。该算法的速度和函数库的速度是差不多的。

1.分别定义:[0...zero]区间表示的是0, [zero+1...two-1]区间表示的是1,[two...n-1]区间表示的是2

2.初始化的时候为无效。i表示当前遍历元素的索引,当为1继续++。

3.当为2的时候,需要和two-1位置的元素交换,并且two-1位置元素并未访问,交换之后不必i++;

4.当为0的时候,需要和zero+1位置的元素交换,由于zero+1的位置已经被访问,故i++

5.注意循环的结束条件。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值