leetcode 4 - Median of Two Sorted Arrays

https://leetcode.com/problems/median-of-two-sorted-arrays/

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 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.
Example 3:

Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Example 4:

Input: nums1 = [], nums2 = [1]
Output: 1.00000
Example 5:

Input: nums1 = [2], nums2 = []
Output: 2.00000

Constraints:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-10^6 <= nums1[i], nums2[i] <= 10^6

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
//O(log(min(len1, len2)))
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() < nums2.size())
return binary_search(nums1, nums2);
else
return binary_search(nums2, nums1);
}

double binary_search(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int l = 0, r = n;

int total = n + nums2.size();

while (l <= r) {
int m = l + (r-l)/2;

int x_min = (m == 0) ? INT_MIN : nums1[m-1];
int x_max = (m == n) ? INT_MAX : nums1[m];

int k = (total + 1) / 2 - m; //left partion size for nums2

int y_min = (k == 0) ? INT_MIN : nums2[k-1];
int y_max = (k == nums2.size()) ? INT_MAX : nums2[k];

if (x_min <= y_max && y_min <= x_max) {
if (total % 2)
return max(x_min, y_min);
else
return (max(x_min, y_min) + min(x_max, y_max)) / 2.0;
} else if (x_min > y_max) {
r = m - 1;
} else {
l = m + 1;
}
}

//should not get here
return 0;
}
};