Problem
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Answer
Complexity: O(log(n+m))
Binary search the first array.
Suppose we want to search the nth element, and the first array’s index is mid, then we will check the second array at the position r_pos = (nth – mid -1).
If r_pos < 0 it means there are too many elements in the first array which is larger than nth, and we should move the current index forward.
If r_pos >=0 and r_pos < size (nums2) and the element of the second array at index r_pos smaller than the element in the first array of index mid, it means the element in the first array is is larger than the nth element, so move the index forward;
Otherwise move the index afterward.
Code
class Solution {
public:
int find(vector<int>& nums1, vector<int>& nums2, int nth) {
int left = 0, right = (int)nums1.size() - 1;
while (left <= right) {
int mid = left + right >> 1;
int l_pos = nth - mid - 1 - 1;
int r_pos = l_pos + 1;
if (r_pos < 0) right = mid - 1;
else if (r_pos < (int)nums2.size() && nums2[r_pos] < nums1[mid]) right = mid - 1;
else left = mid + 1;
}
int cnt = nth - right - 1;
// cout << nth << " " << cnt << " " << right << endl;
if (cnt == 0 || (right >= 0 && nums2[cnt - 1] < nums1[right])) return nums1[right];
else return nums2[cnt - 1];
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if ((nums1.size() + nums2.size()) % 2 == 1)
return find(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1);
else return (find(nums1, nums2, (nums1.size() + nums2.size()) / 2) + find(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
}
};