https://leetcode.com/problems/sort-colors/
这道题用两个指针的方法不难,就是一定要想清楚,调试了几遍才过,数组还是要多练习一下。用counting sort 也不难,只是绕来绕去的,要对counting sort非常熟悉才行。
下面是counting sort的方法:
public void sortColors(int[] A){
int[] helpers = new int[3];
for(int i=0; i<A.length; i++){
helpers[A[i]]++;
}
int[] res = new int[A.length];
for(int i=1; i<3; i++){
helpers[i] = helpers[i-1]+helpers[i];
}
for(int i=(A.length-1); i>=0; i--){
res[helpers[A[i]]-1] = A[i];
helpers[A[i]]--;
}
for(int i=0; i<A.length; i++){
A[i]=res[i];
}
}
下面是两个指针方法:
public void sortColors(int[] A) {
if(A==null || A.length==0) return;
int rpos = 0;
int bpos = A.length-1;
int i=0;
while(i<=bpos && rpos<bpos){
if(A[i]==0){
swap(A, rpos++, i);
i++;
continue;
}
if(A[i]==2){
swap(A, bpos--, i);
continue;
}
i++;
}
}
public void swap(int[] A, int i, int j){
int tmp = A[i];
A[i]=A[j];
A[j]=tmp;
}
第二种方法更节省空间O(1),且只过了一遍数组,第一种方法空间复杂度O(n), 时间复杂度O(n),且过了3遍数组。