Shirlies
宁静专注认真的程序媛~

题目

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

答案

看到题目要求O(log (m+n)),知道应该用二分,但是没有想到具体实施的办法,在网上搜了答案,看懂了完成的代码,这道题刷新了我对二分的看法,神一样的存在。

代码

 1 #define MIN(a,b) ((a) > (b) ? (b) : (a))
 2 
 3 
 4 class Solution {
 5 public:
 6     int findMedNum(vector<int>::iterator nums1Beg,int nums1Num,vector<int>::iterator nums2Beg,int nums2Num,int med)
 7     {
 8         if(nums1Num == 0 )
 9         {
10             return *(nums2Beg + med - 1);
11         }
12         if(nums1Num > nums2Num)
13         {
14             return findMedNum(nums2Beg,nums2Num,nums1Beg,nums1Num,med);
15         }
16         
17         if(med == 1)
18         {
19             return MIN(*nums1Beg,*nums2Beg);
20         }
21         
22         int nums1BegMed = MIN(med / 2, nums1Num);
23         int nums2BegMed = med - nums1BegMed;
24         
25         if(*(nums1Beg + nums1BegMed - 1) == *(nums2Beg + nums2BegMed - 1))
26         {
27             return *(nums1Beg + nums1BegMed - 1);
28         }
29         
30         if(*(nums1Beg + nums1BegMed - 1) < *(nums2Beg + nums2BegMed - 1))
31         {
32             return findMedNum(nums1Beg + nums1BegMed,nums1Num - nums1BegMed,nums2Beg,nums2BegMed,med - nums1BegMed);
33         }
34         
35         if(*(nums1Beg + nums1BegMed - 1) > *(nums2Beg + nums2BegMed - 1))
36         {
37             return findMedNum(nums1Beg,nums1BegMed,nums2Beg + nums2BegMed,nums2Num - nums2BegMed,med - nums2BegMed);
38         }
39         
40         return 0;
41     }
42     
43     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
44         if(nums1.size() == 0 && nums2.size() == 0)
45         {
46             return 0;
47         }
48         int totalLen = nums1.size() + nums2.size();
49         
50         if(totalLen & 0x1)
51         {
52             return findMedNum(nums1.begin(),nums1.size(),nums2.begin(),nums2.size(),(totalLen / 2) + 1);
53         }
54         else
55         {
56             int pre = findMedNum(nums1.begin(),nums1.size(),nums2.begin(),nums2.size(),totalLen / 2);
57             int post = findMedNum(nums1.begin(),nums1.size(),nums2.begin(),nums2.size(),(totalLen / 2) + 1);
58             return (double)(pre + post) / 2.0;
59         }
60         
61         return 0;
62     }
63 };
View Code

 

posted on 2016-08-10 15:15  Shirlies  阅读(294)  评论(0编辑  收藏  举报