首页 > 代码库 > LeetCode "Sort Colors"

LeetCode "Sort Colors"

For the one pass solution... first I tried to build white\blue from red, but not working anyway. Then I referred someone‘ code, to build red\blue from white. Working now. The pointers‘ behavior deserves more thinking:

class Solution {public:    void swap(int A[], int i, int j)    {        int tmp = A[i];        A[i] = A[j];        A[j] = tmp;    }    void sortColors(int A[], int n) {        if (n == 0 || n == 1) return;        if (n == 2)        {            if (A[0] > A[1]) swap(A, 0, 1);            return;        }        int i0 = 0;        int i1 = 0;        int i2 = n - 1;        while (i1<=i2)        {            if (A[i1] == 0)            {                swap(A, i0++, i1++); 
         // Reason i1 also inc here: all 2s have been swapped back,
         // so all left are 0\1s - in any case, we don‘t need consider twice. so move on
continue; } else if (A[i1] == 2) { swap(A, i1, i2--); continue; } i1 ++; } }};