思路:
二分,参考了https://www.cnblogs.com/voidsky/p/5373982.html
实现:
1 class Solution 2 { 3 public: 4 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 5 { 6 int n = nums1.size(), m = nums2.size(); 7 if (n > m) return findMedianSortedArrays(nums2, nums1); 8 int l = 0, r = 2 * n; 9 long long l1, l2, r1, r2; 10 while (l <= r) 11 { 12 int c1 = l + r >> 1, c2 = m + n - c1; 13 l1 = c1 == 0 ? INT_MIN : nums1[c1 - 1 >> 1]; 14 r1 = c1 == 2 * n ? INT_MAX : nums1[c1 >> 1]; 15 l2 = c2 == 0 ? INT_MIN : nums2[c2 - 1 >> 1]; 16 r2 = c2 == 2 * m ? INT_MAX : nums2[c2 >> 1]; 17 if (l1 > r2) r = c1 - 1; 18 else if (l2 > r1) l = c1 + 1; 19 else break; 20 } 21 long long res = max(l1, l2) + min(r1, r2); 22 return (double)res / 2.0; 23 } 24 }