|
| 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 | + } |
| 7 | + int i = 0, j = nums1.size(); |
| 8 | + // bianry search boundary condition |
| 9 | + while(i<=j) |
| 10 | + { |
| 11 | + // initial mid |
| 12 | + int mid = (j-i)/2+i; |
| 13 | + // next mid to consider between the given mid of num1 and mid between num1 and num2 |
| 14 | + int mid2 = (nums1.size()+nums2.size()+1)/2-mid; |
| 15 | + // checking if mid == 0 |
| 16 | + // initialise l1 |
| 17 | + int l1 = (mid==0)?INT_MIN:nums1[mid-1]; |
| 18 | + // intialise l2 |
| 19 | + int l2 = (mid2==0)?INT_MIN:nums2[mid2-1]; |
| 20 | + // initialise r1 and r2 |
| 21 | + int r1 = (mid==nums1.size())?INT_MAX:nums1[mid]; |
| 22 | + int r2 = (mid2==nums2.size())?INT_MAX:nums2[mid2]; |
| 23 | + // check if lvalues are smaller than or equal to the rvalues |
| 24 | + if(l1<=r2 && l2<=r1) |
| 25 | + { |
| 26 | + // return the max value of the lvalues and its odd |
| 27 | + if((nums1.size()+nums2.size()) & 1) |
| 28 | + return (double) max(l1,l2) ; |
| 29 | + // return max lvalue and min rvalue |
| 30 | + else |
| 31 | + return ((double(max(l1,l2)+min(r1,r2))))/2; |
| 32 | + } |
| 33 | + // changing the boundary values acc to the conditions |
| 34 | + else if(l1 > r2) |
| 35 | + j = mid-1; |
| 36 | + else |
| 37 | + i = mid+1; |
| 38 | + } |
| 39 | + return -1.0; |
| 40 | + } |
| 41 | +}; |
0 commit comments