Leetcode 4: Median of Two Sorted Arrays

Problem

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)).


Answer

Complexity: O(log(n+m))
Binary search the first array.
Suppose we want to search the nth element, and the first array’s index is mid, then we will check the second array at the position r_pos = (nth – mid -1).
If r_pos < 0 it means there are too many elements in the first array which is larger than nth, and we should move the current index forward.
If r_pos >=0 and r_pos < size (nums2) and the element of the second array at index r_pos smaller than the element in the first array of index mid, it means the element in the first array is is larger than the nth element, so move the index forward;
Otherwise move the index afterward.

Code

class Solution {
public:
    int find(vector<int>& nums1, vector<int>& nums2, int nth) {
        int left = 0, right = (int)nums1.size() - 1;
        while (left <= right) {
            int mid = left + right >> 1;
            int l_pos = nth - mid - 1 - 1;
            int r_pos = l_pos + 1;
            if (r_pos < 0) right = mid - 1;
            else if (r_pos < (int)nums2.size() && nums2[r_pos] < nums1[mid]) right = mid - 1;
            else left = mid + 1;
        }

        int cnt = nth - right - 1;
      //  cout << nth << " " << cnt << " " << right << endl;
        if (cnt == 0 || (right >= 0 && nums2[cnt - 1] < nums1[right])) return nums1[right];
        else return nums2[cnt - 1];
    }
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if ((nums1.size() + nums2.size()) % 2 == 1)
            return find(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1);
        else return (find(nums1, nums2, (nums1.size() + nums2.size()) / 2) + find(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值