Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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 ++; } } };
posted on 2014-07-22 11:31  Tonix  阅读(128)  评论(0编辑  收藏  举报