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

You may assume nums1 and nums2 cannot be both empty.

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

 1 class Solution {
 2 public:
 3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
 4         if(nums1.size()>nums2.size())
 5             return findMedianSortedArrays(nums2,nums1);
 6         if(0==nums2.size())
 7             return 0.0;
 8         int imin=0,imax=nums1.size(),halflen=(nums1.size()+nums2.size()+1)/2;
 9         
10         while(imin<=imax)
11         {
12             int i=(imin+imax)/2;
13             int j=halflen-i;
14             if(i<nums1.size()&&nums2[j-1]>nums1[i])
15                 imin=i+1;
16             else if(i>0&&nums1[i-1]>nums2[j])
17                 imax=i-1;
18             else
19             {
20                 int max_of_left;
21                 if(0==i)
22                     max_of_left=nums2[j-1];
23                 else if(0==j)
24                     max_of_left=nums1[i-1];
25                 else
26                     max_of_left=max(nums1[i-1],nums2[j-1]);
27                 
28                 if((nums1.size()+nums2.size())%2==1)
29                     return max_of_left;
30                 
31                 int min_of_right;
32                 if(i==nums1.size())
33                     min_of_right=nums2[j];
34                 else if(j==nums2.size())
35                     min_of_right=nums1[i];
36                 else
37                     min_of_right=min(nums1[i],nums2[j]);
38                 return (max_of_left+min_of_right)/2.0;
39             }
40         }
41         return 0;
42     }
43 };

 

根据排名第一的答案翻译成cpp的版本, 实在是强大的思想.

https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2481/Share-my-O(log(min(mn)))-solution-with-explanation