标签:dia and EDA complex har out art begin bsp
題目:
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)).
Code:
1 class Solution 2 { 3 public: 4 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 5 { 6 int m = nums1.size(), n = nums2.size(); 7 int res1 = findKth(nums1, nums2, (m + n + 1) / 2); 8 int res2 = findKth(nums1, nums2, (m + n + 2) / 2); 9 return (res1 + res2) / 2.0; 10 } 11 12 private: 13 int findKth(vector<int> nums1, vector<int>nums2, int k) 14 { 15 int m = nums1.size(), n = nums2.size(); 16 //always assume that m is equal or smaller than n 17 if (m > n) 18 return findKth(nums2, nums1, k); 19 //nums1 equal null return nums2 20 if (m == 0) 21 return nums2[k - 1]; 22 if (k == 1) 23 return min(nums1[0], nums2[0]); 24 25 int i = min(m, k / 2), j = min(n, k / 2); 26 //divide k into two parts 27 if (nums1[i - 1] > nums2[j - 1]) 28 return findKth(nums1, vector<int>(nums2.begin() + j, nums2.end()), k - j); 29 else if (nums1[i - 1] < nums2[j - 1]) 30 return findKth(vector<int>(nums1.begin() + i, nums1.end()), nums2, k - i); 31 return 0; 32 } 33 }; 34 35 36 int main() 37 { 38 Solution sol; 39 vector<int> a{ 1, 2, 3, 5 }; 40 vector<int> b{ 6, 7, 8, 9 }; 41 double res = sol.findMedianSortedArrays(a, b); 42 cout << res << endl; 43 44 system("pause"); 45 return 0; 46 }
(Leetcode) Median of Two Sorted Arrays (Hard)
标签:dia and EDA complex har out art begin bsp
原文地址:https://www.cnblogs.com/ollie-lin/p/8969966.html