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