二分题

Posted redips

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分题相关的知识,希望对你有一定的参考价值。

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

 

以上是关于二分题的主要内容,如果未能解决你的问题,请参考以下文章

记录一次面试中二分查找的算法题

二分图匹配入门专题1I - Hiding Gold light oj 1152二分图匹配-------------------我是终于不那么水的水题分割线------------------(代码片

二分图相关题

蓝桥杯刷题笔记:二分查找

开启力扣刷题之路 >数组> 二分法

前端面试题之手写promise