Sort Colors

三个指针,就是比较容易糊涂,要想清楚

public class Solution {
    public void sortColors(int[] A) {
        if(A==null || A.length<2) return;
        int p0=0, p2 = A.length-1;
        while(p0<A.length-1 && A[p0]==0){
            p0++;
        }
        if(p0==A.length-1) return;
       
        while(p2>0 && A[p2]==2){
            p2--;
        }
        if(p2==0) return;
         int pm = p0;
        while(pm<=p2){
            if(A[pm]==0){
                swap(A, pm, p0);
                p0++;
                pm++;
            }else if(A[pm]==2){
                swap(A, pm, p2);
                p2--;
            }else
                pm++;
        }
    }
        
    public void swap(int[] A,int i,int j){
        int t = A[i];
        A[i]=A[j];
        A[j]=t;
    }
}

另一种做法是计数排序,值得学习一下

public class Solution {
    public void sortColors(int[] A) {
        // http://blog.csdn.net/linhuanmars/article/details/24286349
        if(A==null || A.length<2) return;
        int[] helper = new int[3];
        int[] res = new int[A.length];
        for(int i:A){
            helper[i]++;
        }
        for(int i=1;i<helper.length;i++){
            helper[i] = helper[i]+helper[i-1]; // find the starting pos for each element
        }
        for(int i=0;i<A.length;i++){
            res[helper[A[i]]-1] = A[i]; //!!!
            helper[A[i]]--;             //!!!
        }
        for(int i=0; i<A.length;i++){
            A[i] = res[i];
        }
    }
}

 

posted @ 2015-04-16 11:05  世界到处都是小星星  阅读(131)  评论(0编辑  收藏  举报