LintCode "Interleaving Positive and Negative Numbers"

Partition and swapping. A lot details to take care.

class Solution {
public:
    /**
     * @param A: An integer array.
     * @return: void
     */
    void rerange(vector<int> &A) {
        int n = A.size();
        if(n < 3) return;

        // partition
        int j0 = 0, j1 = 0;
        while(j1 < n)
        {
            if(A[j1] > 0)
            {
                j1 ++;
            }
            else
            {
                swap(A[j0++], A[j1]);
                j1 = j0;
            }
        }
        //  swap
        int i0 = (j0 * 2) < n ? 0 : 1, i1 = j0;
        while(i0 < n && i1 < n)
        {
            if(A[i0] > 0) break;
            swap(A[i0], A[i1 ++]);
            i0 += 2;
        }
    }
};
原文地址:https://www.cnblogs.com/tonix/p/4851060.html