leetcode-75 Sort Colors

来源:互联网 发布:电视直播软件 知乎 编辑:程序博客网 时间:2024/05/22 07:58

因为待排序的数字的大小在一个很小的范围之内(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>


0 0
原创粉丝点击