-
Notifications
You must be signed in to change notification settings - Fork 41
/
Median_Of_Two_Sorted_Array.cpp
58 lines (43 loc) · 1.45 KB
/
Median_Of_Two_Sorted_Array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*Problem Statement:-
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
*/
/*---------------------------------------SOLUTION---------------------------------*/
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m=nums1.size();
int n=nums2.size();
if(m>n){
return findMedianSortedArrays(nums2,nums1);
}
int low = 0, high = m;
while(low<=high){
int cut1 = (low+high)/2;
int cut2 = (m+n+1)/2-cut1;
int l1 = (cut1==0)?INT_MIN:nums1[cut1-1];
int l2 = (cut2==0)?INT_MIN:nums2[cut2-1];
int r1 = (cut1==m)?INT_MAX:nums1[cut1];
int r2 = (cut2==n)?INT_MAX:nums2[cut2];
if(l1<=r2 && l2<=r1){
if((m+n)%2==0){
return (max(l1,l2)+min(r1,r2))/2.0;
}else{
return max(l1,l2);
}
}else if(l1>r2){
high=cut1-1;
}else{
low=cut1+1;
}
}
return 0.0;
}
};