[leetcode]Sort Colors

荷兰三色旗问题。学以致用,理解更深刻了。顺便参看一下非常精简的一个解法,其实本质一样:http://discuss.leetcode.com/questions/251/sort-colors

public class Solution {

    public void sortColors(int[] A) {

        // Start typing your Java solution below

        // DO NOT write main() function

        int len = A.length;

        if (len == 0) return;

        

        int i = 0;

        while (i < len && A[i] == 0) i++;

        

        int j = len - 1;

        while (j >= 0 && A[j] == 2) j--;

        

        for (int k = i; k <= j;) {

            if (A[k] == 0) {

        		int tmp = A[i];

        		A[i] = A[k];

        		A[k] = tmp;

        		

        		i++;

        		if (k < i) k = i;

        	}

        	else if (A[k] == 2) {

        		int tmp = A[j];

        		A[j] = A[k];

        		A[k] = tmp;

        		j--;

        	}

        	else {k++;}

        }

    }

}

  

你可能感兴趣的:(LeetCode)