leetcode No75. Sort Colors

来源:互联网 发布:网络十大丑男照片 编辑:程序博客网 时间:2024/06/10 08:26

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.

Algorithm:

法一:计数排序,就三个数,分别记下0,1,2的个数,k1、k2、k3。然后置新数组的前k1个数为0,后k2个数为1,剩下的为2。
法二:类似两路快排的思想,即把数组分割为<v,==v,>v三部分

Accepted Code:

法一:
class Solution {  //计数排序public:    void sortColors(vector<int>& nums) {        int k0=0;        int k1=0;        int k2=0;        for(int i=0;i<nums.size();i++)        {            if(nums[i]==0)                k0++;            else if(nums[i]==1)                k1++;            else                 k2++;        }        for(int i=0;i<nums.size();i++)        {            if(i<k0)                 nums[i]=0;            else if(i<(k0+k1))                nums[i]=1;            else                 nums[i]=2;        }    }};
法二:
class Solution {public:    void sortColors(vector<int>& nums) {        int l=0;            //0  保证nums[0...<l)==0        int r=nums.size();  //2  保证nums[r...<n)==2        int i=0;            //1  保证nums[l...<i)==1        while(i<r)        {            if(nums[i]==0)            {                swap(nums[i++],nums[l++]);            }            else if(nums[i]==2)   //从右边换过来的数是不确定的,所以i不自加            {                swap(nums[i],nums[--r]);            }            else                   i++;        }                return;    }};






0 0