forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedian-sorted-array.cpp
36 lines (32 loc) · 1.24 KB
/
median-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
// Question Link : https://leetcode.com/problems/median-of-two-sorted-arrays
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n1 = nums1.size(), n2 = nums2.size();
//if n1 is bigger swap the arrays:
if (n1 > n2) return findMedianSortedArrays(nums2, nums1);
int n = n1 + n2; //total length
int left = (n1 + n2 + 1) / 2; //length of left half
//apply binary search:
int low = 0, high = n1;
while (low <= high) {
int mid1 = (low + high) >> 1;
int mid2 = left - mid1;
//calculate l1, l2, r1 and r2;
int l1 = INT_MIN, l2 = INT_MIN;
int r1 = INT_MAX, r2 = INT_MAX;
if (mid1 < n1) r1 = nums1[mid1];
if (mid2 < n2) r2 = nums2[mid2];
if (mid1 - 1 >= 0) l1 = nums1[mid1 - 1];
if (mid2 - 1 >= 0) l2 = nums2[mid2 - 1];
if (l1 <= r2 && l2 <= r1) {
if (n % 2 == 1) return max(l1, l2);
else return ((double)(max(l1, l2) + min(r1, r2))) / 2.0;
}
//eliminate the halves:
else if (l1 > r2) high = mid1 - 1;
else low = mid1 + 1;
}
return 0;
}
};