Median of Two Sorted Arrays
Binary Search; Hard;
Last updated
Binary Search; Hard;
Last updated
给定两个有序数组arr1和arr2,已知两个数组的长度都为N,求两个数组中所有数的上中位数。上中位数:假设递增序列长度为n,若n为奇数,则上中位数为第n/2+1个数;否则为第n/2个数[要求]时间复杂度为O(logN)O(logN),额外空间复杂度为O(1)O(1)
输入:
复制返回值:
复制说明:
输入:
复制返回值:
复制说明:
method 1: merge and sort
First merge and sort two array
find the middle element as median of two array
Time: O(n), Space: O(n)
method 2: binary search
Define left, right pointers of arr1 = l1, r1 and left, right pointers of arr2 = l2, r2
Since two sorted arrays have same length, so first find the middle elements of two arrays (two medians of two array)
if arr1[mid1] == arr2[mid2] -> two arrays have the same median and this is the global median
if arr1[mid1] > arr2[mid2], then arr1[mid1] is on the right hand side of arr2[mid2] in the global array. That is, arr1[mid1] >= global median >= arr2[mid2]. So we need to search the left space of arr1[mid1] and the right space of arr2[mid2]. So let l1 = mid1, r2 = mid2
if arr1[mid1] < arr2[mid2], similary, arr1[mid1] <= global median <= arr2[mid2]. So let r1 = mid1, l2 = mid2.
repeat step 1~5 while l1 < r1
Note:
when l1=r1-1, compute middle between l1, r1 could lead to dead loop, since l1 = mid1 always. When subarray arr1[l1:r1+1] has even size, we need l1 = mid1 + 1 and l2 = mid1 + 1
Time: O(logn), Space: O(1)
method 1:
method 2: