forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0004-median-of-two-sorted-arrays.cpp
62 lines (51 loc) · 1.72 KB
/
0004-median-of-two-sorted-arrays.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
59
60
61
62
/*
Given 2 sorted arrays of size m & n, return the median of these arrays
Ex. nums1 = [1,3] nums2 = [2] -> 2, nums1 = [1,2] nums2 = [3,4] -> 2.5
Binary search, partition each array until partitions are correct, get median
[1,2,3,4,5]
| a|b |
[1,2,3,4,5,6,7,8] --> a <= d ? yes, c <= b ? no, so need to fix
| c|d |
Time: O(log min(m, n))
Space: O(1)
*/
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 total = m + n;
int low = 0;
int high = m;
double result = 0.0;
while (low <= high) {
// nums1
int i = low + (high - low) / 2;
// nums2
int j = (total + 1) / 2 - i;
int left1 = (i > 0) ? nums1[i - 1] : INT_MIN;
int right1 = (i < m) ? nums1[i] : INT_MAX;
int left2 = (j > 0) ? nums2[j - 1] : INT_MIN;
int right2 = (j < n) ? nums2[j] : INT_MAX;
// partition is correct
if (left1 <= right2 && left2 <= right1) {
// even
if (total % 2 == 0) {
result = (max(left1, left2) + min(right1, right2)) / 2.0;
// odd
} else {
result = max(left1, left2);
}
break;
} else if (left1 > right2) {
high = i - 1;
} else {
low = i + 1;
}
}
return result;
}
};