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

二分题

时间:2018-01-18 23:09:06      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:another   array   blog   计算   数列   not   ble   script   find   

1. leetcode.4 Median of Two Sorted Arrays

找两个有序数列的中位数。要求log(m+n)。

------------------------------------------------------------------

二分,从b中找a.middle,计算小于等于a.middle的数的个数left。

double findMedianSortedArrays(vector<int>& a, vector<int>& b) {
    int as = 0, ae = a.size();
    int bs = 0, be = b.size();
    int goal = (ae + be) / 2;
    while (as<ae&&bs<be){
        int mida = (as + ae) / 2;
        int posb = std::lower_bound(b.begin() + bs, b.begin() + be, a[mida]) - b.begin();
        int left = posb - bs + mida - as + 1;
        if (goal == left){
            posb = (a.size() + b.size()) / 2 - mida - 1;
            int next;
            if (posb >= 0 && posb<b.size()) {
                next = b[posb];
                if (mida + 1 < a.size()) next = std::min(next, a[mida + 1]);
            }
            else next = a[mida + 1];
            if ((a.size() + b.size()) % 2) return next;
            return (next + a[mida])*0.5;
        }
        else if (left>goal){
            ae = mida;
            be = posb;
        }
        else{
            as = mida + 1;
            bs = posb;
            goal -= left;
        }
    }
    if (as<ae){
        int another = (a.size() + b.size()) / 2 - (as + goal);
        int next;
        if (another >= 0 && another < b.size()){
            next = b[another];
            if (as + goal < a.size()) next = min(next, a[as + goal]);
        }
        else next = a[as + goal];
        if ((a.size() + b.size()) % 2) return next;
        return (next + a[as + goal - 1])*0.5;
    }
    else{
        int another = (a.size() + b.size()) / 2 - (bs + goal);
        int next;
        if (another >= 0 && another < a.size()){
            next = a[another];
            if (bs + goal < b.size()) next = min(next, b[bs + goal]);
        }
        else next = b[bs + goal];
        if ((a.size() + b.size()) % 2) return next;
        return (next + b[bs + goal - 1])*0.5;
    }
}

 

二分题

标签:another   array   blog   计算   数列   not   ble   script   find   

原文地址:https://www.cnblogs.com/redips-l/p/8313165.html

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