• 二分


    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;
        }
    }
  • 相关阅读:
    【BZOJ1053】[HAOI2007]反素数
    【BZOJ1052】[HAOI2007]覆盖问题
    【BZOJ1051】[HAOI2006]受欢迎的牛
    【BZOJ1050】[HAOI2006]旅行
    laravel 操作多数据库总结
    微服务浅述---架构演进
    分布式锁
    laravel自动生成model
    springboot集成quartz实现任务调度
    laravel 队列服务使用总结
  • 原文地址:https://www.cnblogs.com/redips-l/p/8313165.html
Copyright © 2020-2023  润新知