4. Median of Two Sorted Arrays
Problem description:
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)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Solution:
The median is used for dividing a set into two equal length
subsets, that one subset is always greater than the other
If the total number of elements are odd, then what we have to do is to find the K
th number of element.
If the total number of elements are even, then what we have to do is to find the K
th and K+1
number of element, then divided it to half to get the median.
For example:3 4 5 6 7 8
, the median is 5.5
3 4 5 6 7 8 9
, the median is 6
- find the total length
1 | class Solution { |
time complexity: $O()$
space complexity: $O()$
reference: