leetcode-75 Sort Colors

因为待排序的数字的大小在一个很小的范围之内(0-2),所以可以使用这种算法:

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

剑指offer上也有类似的题目(65页),该算法的时间复杂度为O(n)

void sortColors(int A[], int n) {
    int timesOfColor[3] = {0};
    int i,k,m;
    for(i = 0; i < n; i++){
       int j = A[i];
       timesOfColor[j]++;
    }
    m = 0;
    for(i = 0; i < 3; i++){
        for(k = 0; k < timesOfColor[i]; k++){
            A[m++] = i;
        }
    }
}

另外一种投票很多,比较通用的方法

void sortColors(int A[], int n) {
   int i = -1,j = -1,k = -1;
   int m;
   for(m = 0; m < n; m++){
       if(A[m] == 0){
           A[++k] = 2;
           A[++j] = 1;
           A[++i] = 0;
       }else if(A[m] == 1){
           A[++k] = 2;
           A[++j] = 1;
       }else if(A[m] == 2){
           A[++k] = 2;
       }
   }
}
对于这种方法,比较坑爹的是我去掉两个else,就通不过([0,0,1,0,1,1]),很奇怪
还有另外一种比较容易想到的方法,一遍扫描,将0交换到最左边,2交换到最右边。这种方法需要 注意 的地方是:将2交换到右边后,还需要对交换回来的数进行一次检查

<span style="color:#333333;">void swap(int A[],int i,int j){
    int tmp;
    tmp = A[j];
    A[j] = A[i];
    A[i] = tmp;
}
void sortColors(int A[], int n) {
   if(A == NULL || n <= 0){
       return ;
   }
   int low = 0,high = n;
   int i;
   for(i = 0; i < high; i++){
       if(A[i] == 2){
           swap(A,</span><strong><span style="color:#ff0000;">i--</span></strong><span style="color:#333333;">,--high);
       }else if(A[i] == 0){
           swap(A,i,low++);
       }
   }
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值