码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Interleaving Positive and Negative Numbers"

时间:2015-10-01 16:30:24      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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;
        }
    }
};

LintCode "Interleaving Positive and Negative Numbers"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4851060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!