75. Sort Colors(unsolved)

本文介绍了一种高效的算法,用于将一个包含红色、白色和蓝色对象的数组进行排序,使得相同颜色的对象相邻,并按照红、白、蓝的顺序排列。通过使用0、1、2分别代表红色、白色和蓝色,该算法利用三个指针red、i和blue来实现快速排序。

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指针指向开头,一个blue指针指向结尾。然后用i遍历,如果遇到0
,那么与red交换,如果遇到2,那么与blue交换。如果遇到1,那么不用交换。应该注意到:
1.与blue交换后,i–
2. 与i是遍历到blue的。

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

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值