zoukankan      html  css  js  c++  java
  • 二分

    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;
        }
    }
  • 相关阅读:
    洛谷P2062 分队问题
    bzoj1800 飞行棋
    UVA11100 The Trip, 2007
    UVA11134 Fabled Rooks
    每天一道博弈论之“威佐夫博弈”
    每天一道博弈论之“A game”(伪博弈
    每天一道博弈论之“谁能赢呢?”
    每天一道博弈论之“牛的数字游戏”
    每天一道博弈论之“E&D”
    每天一道博弈论之“巴什博弈”
  • 原文地址:https://www.cnblogs.com/redips-l/p/8313165.html
Copyright © 2011-2022 走看看