leetcode 75 sort colors 数组问题

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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
  • Could you come up with a one-pass algorithm using only constant space?

思路:计数排序 统计0 1 2 出现的次数;

class Solution {
public:
    //0  1  2
    void sortColors(vector<int>& nums)
    {
        int n=nums.size();
        int count0=0;
        int count1=0;
        int count2=0;
        for(auto val:nums)
        {
            if(val==0)
                count0++;
            else if(val==1)
                count1++;
            else if(val==2)
                count2++;
        }
        int i=0;
       while(i<count0)
       {
           nums[i]=0;
           i++;
       }
        int j=0;
        while(j<count1)
        {
            nums[i+j]=1;
            j++;
        }
        int k=0;
        while(k<count2)
        {
            nums[k+i+j]=2;
            k++;
        }
    }
};

其他的代码:

    void sortColors(vector<int>& nums)
    {
        int count[3]={0};
        int n=nums.size();
        for(auto i:nums)
        {
            assert(i>=0&&i<=2);
            count[i]++;
        }
        int index=0;
        for(int i=0;i<count[0];i++)
            nums[index++]=0;
        for(int i=0;i<count[1];i++)
            nums[index++]=1;
        for(int i=0;i<count[2];i++)
            nums[index++]=2;
    }   

三路快排的思路:

  //只遍历了数组一次;非常的酷   三路快排的思路;
    void sortColors(vector<int>& nums)
    {
        int n=nums.size();
        if(n==0)
            return ;
        int zero=-1;//nums[0...zero]=0;
        int two=n;//nums[two....n-1]=2;两个都是无效的数组;
        for(int i=0;i<two;)
        {
            if(nums[i]==1)
                i++;
            else if(nums[i]==2)
                swap(nums[--two],nums[i]);
            else 
                swap(nums[++zero],nums[i++]);
        }
    }

猜你喜欢

转载自blog.csdn.net/langxue4516/article/details/81346330