leetcode 寻找两个有序数组的中位数
2019-06-17 17:31
309 查看
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
思路:
根据二分查找:
1、nums1,nums2分为左右部分;
2、如果nums1左半比nums2的右半要大,说明中位数在nums2的右半和nums1的左半之间,继续二分。
如果nums1右半比nums2的左半小,说明中位数在nums1的右半和nums2的左半之间,继续二分。
3、将左半合并,右半合并,取中位数。
类似于大顶堆,小顶堆思想。
[code]def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: lenn=len(nums1)+len(nums2) minValue = -1 maxValue = 999999999999999999999999 len1 = len(nums1) len2 = len(nums2) if len1 > len2: len1, len2, nums1, nums2 = len2, len1, nums2, nums1 cutL = 0 cutR = len1 cut1 = len1 // 2 cut2 = lenn // 2 - cut1 while cut1 <= len1: L1 = minValue if cut1 == 0 else nums1[cut1 - 1] R1 = maxValue if cut1 == len1 else nums1[cut1] L2 = minValue if cut2 == 0 else nums2[cut2 - 1] R2 = maxValue if cut2 == len2 else nums2[cut2] if L1 > R2: cutR = cut1 - 1 elif L2 > R1: cutL = cut1 + 1 else: if lenn % 2 == 0: l = max(L1, L2) r = min(R1, R2) return (l + r) / 2 else: return min(R1, R2) cut1 = (cutR - cutL) // 2 + cutL cut2 = lenn // 2 - cut1
相关文章推荐
- Python学习-Leetcode刷题记2:寻找两个有序数组的中位数
- Leetcode(C++)——4. 寻找两个有序数组的中位数
- LeetCode4 寻找两个有序数组的中位数 Median of Two Sorted Arrays
- Datawhale-LeetCode集训打卡-寻找两个有序数组的中位数
- leetcode--寻找两个有序数组的中位数
- leetcode 4. 寻找两个有序数组的中位数(Java版)
- LeetCode刷题-寻找两个有序数组的中位数
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- leetCode---寻找两个有序数组的中位数
- 基础算法之寻找两个有序数组的中位数(LeetCode-4)
- 【leetcode】4. 寻找两个有序数组的中位数
- Leetcode-寻找两个有序数组的中位数
- leetcode 寻找两个有序数组的中位数
- LeetCode题解(python)-4. 寻找两个有序数组的中位数
- 【LeetCode】第四题:寻找两个有序数组的中位数
- LeetCode第4题--寻找两个有序数组的中位数
- LeetCode-4 :寻找两个有序数组的中位数 ★★★★★
- leetcode 4.寻找两个有序数组的中位数
- LeetCode--4. 寻找两个有序数组的中位数(Median of Two Sorted Arrays)
- leetcode 寻找两个有序数组的中位数 median of two sorted arrays