[leetcode] 4. Median of Two Sorted Arrays

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

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

 

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5


非常有趣的二分查找题目,首先假设,这个中位数一定来自数组nums1,那么有如下:

  1. 在nums1里面二分下标,对每个下标对应的元素,计算其在nums2中最靠前能排到多少名,最靠后能排到多少名,主要是靠重复元素的存在。那么此元素在nums1里面的排名加上其在nums2里面的排名区间,即可判断此元素是否就是中位数。

  2. 还需要假设此元素在nums2中

  3. 需要考虑合并后的长度是奇数还是偶数

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 double bsearch(vector<int>& nums1, vector<int>& nums2, int pos) {
 5     int low = 0,high = nums1.size()-1, tar = -1;
 6     while(low <= high) {
 7         int mid = (low + high) >> 1;
 8         int val = nums1[mid];
 9         int x = lower_bound(nums2.begin(),nums2.end(),val) - nums2.begin();
10         int y = upper_bound(nums2.begin(), nums2.end(),val) - nums2.begin();
11         if (mid + x <= pos and pos <= mid + y) {
12             tar = nums1[mid];
13             break;
14         } else if (mid + x > pos) high = mid - 1;
15         else low = mid + 1;
16     }
17     return tar;
18 }
19 
20 
21 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
22     int tlen = nums1.size() + nums2.size();
23     double ret = 0;
24 
25     int pos = tlen>>1;
26     ret = bsearch(nums1, nums2, pos);
27     if (ret == -1) ret = bsearch(nums2, nums1, pos);
28 
29     if ((tlen&1) == 0) {
30         pos = (tlen>>1)-1;
31         double tmp = bsearch(nums1, nums2, pos);
32         if (tmp == -1) tmp = bsearch(nums2, nums1, pos);
33         ret += tmp;
34         ret *= 0.5;
35     }
36 
37     return ret;
38 
39 }
40 
41 
42 
43 int main() {
44     vector<int>a = {1,2};
45     vector<int>b = {3,4};
46     cout<<findMedianSortedArrays(a,b)<<endl;
47     return 0;
48 }
View Code

 

posted @ 2017-09-04 10:44  狂徒归来  阅读(201)  评论(0编辑  收藏  举报