2014年5月10日星期六

Loop Solution - Sort Colors

The idea is to group all one color, like 0 then another one, then last one. After every group the begin index will stay at next ready color, so that reduce the cost.

There is another solution to count each colors then rewrite the array.

public class Solution {
    public void sortColors(int[] A) {
        if(A == null || A.length < 2){
            return;
        }
        int cur = 0;
        int beg = 0;
        while(cur < 2 && beg < A.length - 1){
            int next = beg + 1;
            while(next < A.length){
                if(A[beg] == cur){
                    beg++;
                    next = beg + 1;
                }else{
                    if(A[next] == cur){
                        A[next] = A[beg];
                        A[beg] = cur;
                        beg++;
                    }
                    next++;
                }
            }
            cur++;
        }
    }
}

没有评论: