[leetcode]75. Sort Colors

本文介绍了一种将红、白、蓝三种颜色的数组进行排序的方法。使用整数0、1、2来表示红、白、蓝。提出了三种排序方法:计数排序、改进版的荷兰国旗问题算法以及一种通过多次遍历的解决方案。

题目链接:https://leetcode.com/problems/sort-colors/#/description

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.

方法一:

思路:计数排序

class Solution{
public:
    void sortColors(vector<int>& nums)
    {
        int size=nums.size();
        int i=0,j=0,k=0;
        for(int p=0;p<size;p++)
        {
            if(nums[p]==0)
                i++;
            else if (nums[p]==1)
                j++;
            else if(nums[p]==2)
                k++;
        }
        for(int p=0;p<size;p++)
        {
            if(p<i)
                nums[p]=0;
            else if(p>=i && p<i+j)
                nums[p]=1;
            else
                nums[p]=2;
        }
    }
};

方法二:

思路:left记录左边第一个1的位置,right记录第一个2左边的位置,left的左边全是0,right的右边全是2。

          从左到右扫描一次,遇到0就换到左边,遇到1就跳过,遇到2就换到右边,由于left记录的肯定是1,所以交换后i要前进一次,由于right记录的可能是0,可能是1,所以交换后,i不能前进,

class Solution{
public:
    void sortColors(vector<int>& nums)
    {
        int size=nums.size();
        int left=0,right=size-1;
        int i=0;
        while(i<=right)
        {
            if(nums[i]==0)
            {
                swap(nums[i],nums[left]);
                left++;
                i++;
            }
            else if(nums[i]==1)
            {
                i++;
            }
            else
            {
                swap(nums[i],nums[right]);
                right--;
            }
        }
    }
};

方法三:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值