• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
4. Median of Two Sorted Arrays *HARD* -- 查找两个排序数组的中位数(寻找两个排序数组中第k大的数)

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

t int MAX = 0x7fffffff, MIN = 0x80000000;
int kth(vector<int>& nums1, vector<int>& nums2, int sz1, int sz2, int k)
{
#define N1(i) (i<1?MIN:(i>sz1?MAX:nums1[i-1]))
#define N2(i) (i<1?MIN:(i>sz2?MAX:nums2[i-1]))
    int l, r, x;
    l = 0;
    r = sz1;
    while (l <= r)
    {
        x = (l + r) >> 1;
        if (N1(x) > N2(k - x + 1))
            r = x - 1;
        else if (N1(x + 1) < N2(k - x))
            l = x + 1;
        else
            return max(N1(x), N2(k - x));
    }
    return 0; //should not get here
#undef N1
#undef N2
}

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    int sz1 = nums1.size(), sz2 = nums2.size(), sz = sz1 + sz2;
    if (sz1 > sz2)
        return findMedianSortedArrays(nums2, nums1);
    if (sz & 1)
        return kth(nums1, nums2, sz1, sz2, (sz >> 1) + 1);
    return (kth(nums1, nums2, sz1, sz2, sz >> 1) + kth(nums1, nums2, sz1, sz2, (sz >> 1) + 1)) / 2.0;
}

 

posted on 2016-03-07 00:00  ArgenBarbie  阅读(183)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3