代码拉取完成,页面将自动刷新
/**
* Question Link: https://leetcode.com/problems/median-of-two-sorted-arrays/
* Primary idea: Search kth value of both arrays and then compare, each time
* remove half of them until index is 0
*
* Time Complexity: O(log(m + n)), Space Complexity: O(1)
*/
class MedianTwoSortedArrays {
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
let m = nums1.count
let n = nums2.count
return (findKth(nums1, nums2, (m + n + 1) / 2) + findKth(nums1, nums2, (m + n + 2) / 2)) / 2
}
private func findKth(_ nums1: [Int], _ nums2: [Int], _ index: Int) -> Double {
let m = nums1.count
let n = nums2.count
guard m <= n else {
return findKth(nums2, nums1, index)
}
guard m != 0 else {
return Double(nums2[index - 1])
}
guard index != 1 else {
return Double(min(nums1[0], nums2[0]))
}
let i = min(index / 2, m)
let j = min(index / 2, n)
if nums1[i - 1] < nums2[j - 1] {
return findKth(Array(nums1[i..<m]), nums2, index - i)
} else {
return findKth(nums1, Array(nums2[j..<n]), index - j)
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。