leetcode-【hard】4. Median of Two Sorted Arrays

題目html

There are two sorted arrays nums1 and nums2 of size m and n respectively.ide

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).post

Example 1:spa

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

The median is 2.0

 

Example 2:code

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

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

答案htm

看到題目要求O(log (m+n)),知道應該用二分,可是沒有想到具體實施的辦法,在網上搜了答案,看懂了完成的代碼,這道題刷新了我對二分的見解,神同樣的存在。blog

代碼get

 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
相關文章
相關標籤/搜索