- Difficulty: Hard
- Related Topics: Array, Binary Search, Divide and Conquer
- Link: https://leetcode.com/problems/median-of-two-sorted-arrays/
Description
Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
给定两有序数组 nums1
和 nums2
,二者的大小分别为 m
和 n
,返回这两组数的中位数。
Follow up
The overall run time complexity should be (O(log (m + n)))
总时间复杂度应为 (O(log (m + n)))
Examples
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
-106 <= nums1[i], nums2[i] <= 1e6
Solution
这题我也是看了题解才明白个大概。参考文章见后,代码如下:
import kotlin.math.max
import kotlin.math.min
class Solution {
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
// 该算法需保证 nums2 更大
if (nums1.size > nums2.size) {
return findMedianSortedArrays(nums2, nums1)
}
var iMin = 0
var iMax = nums1.size
val halfLen = (nums1.size + nums2.size + 1) / 2
while (iMin <= iMax) {
val i = (iMin + iMax) / 2
val j = halfLen - i
if (i < nums1.size && nums2[j - 1] > nums1[i]) {
iMin = i + 1
} else if (i > 0 && nums1[i - 1] > nums2[j]) {
iMax = i - 1
} else {
val maxOfLeft = when {
i == 0 -> nums2[j - 1]
j == 0 -> nums1[i - 1]
else -> max(nums1[i - 1], nums2[j - 1])
}
if ((nums1.size + nums2.size) % 2 == 1) {
return maxOfLeft.toDouble()
}
val minOfRight = when {
i == nums1.size -> nums2[j]
j == nums2.size -> nums1[i]
else -> min(nums1[i], nums2[j])
}
return (maxOfLeft + minOfRight) / 2.0
}
}
return 0.0
}
}