|
| 1 | +// Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. |
| 2 | + |
| 3 | +// The overall run time complexity should be O(log (m+n)). |
| 4 | + |
| 5 | +// Example 1: |
| 6 | + |
| 7 | +// Input: nums1 = [1,3], nums2 = [2] |
| 8 | +// Output: 2.00000 |
| 9 | +// Explanation: merged array = [1,2,3] and median is 2. |
| 10 | +// Example 2: |
| 11 | + |
| 12 | +// Input: nums1 = [1,2], nums2 = [3,4] |
| 13 | +// Output: 2.50000 |
| 14 | +// Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | +//Approach 1 |
| 20 | + |
| 21 | +class Solution { |
| 22 | +public: |
| 23 | + double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { |
| 24 | + for(int i=0;i<nums2.size();i++){ |
| 25 | + nums1.push_back(nums2[i]); |
| 26 | + } |
| 27 | + sort(nums1.begin(),nums1.end()); |
| 28 | + int n=nums1.size(); |
| 29 | + double res; |
| 30 | + if(n&1) |
| 31 | + res=nums1[n/2]; |
| 32 | + else if(!(n&1)) |
| 33 | + res=(double)(nums1[n/2]+nums1[(n/2)-1])/2; |
| 34 | + |
| 35 | + return res; |
| 36 | + |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | + |
| 41 | +// Approach 2 |
| 42 | + |
| 43 | +class Solution { |
| 44 | +public: |
| 45 | + double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { |
| 46 | + if(nums2.size() < nums1.size()) return findMedianSortedArrays(nums2, nums1); |
| 47 | + int n1 = nums1.size(); |
| 48 | + int n2 = nums2.size(); |
| 49 | + int low = 0, high = n1; |
| 50 | + |
| 51 | + while(low <= high) { |
| 52 | + int cut1 = (low+high) >> 1; |
| 53 | + int cut2 = (n1 + n2 + 1) / 2 - cut1; |
| 54 | + |
| 55 | + |
| 56 | + int left1 = cut1 == 0 ? INT_MIN : nums1[cut1-1]; |
| 57 | + int left2 = cut2 == 0 ? INT_MIN : nums2[cut2-1]; |
| 58 | + |
| 59 | + int right1 = cut1 == n1 ? INT_MAX : nums1[cut1]; |
| 60 | + int right2 = cut2 == n2 ? INT_MAX : nums2[cut2]; |
| 61 | + |
| 62 | + |
| 63 | + if(left1 <= right2 && left2 <= right1) { |
| 64 | + if( (n1 + n2) % 2 == 0 ) |
| 65 | + return (max(left1, left2) + min(right1, right2)) / 2.0; |
| 66 | + else |
| 67 | + return max(left1, left2); |
| 68 | + } |
| 69 | + else if(left1 > right2) { |
| 70 | + high = cut1 - 1; |
| 71 | + } |
| 72 | + else { |
| 73 | + low = cut1 + 1; |
| 74 | + } |
| 75 | + } |
| 76 | + return 0.0; |
| 77 | + } |
| 78 | +}; |
0 commit comments