leetcode 4
题目描述
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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目解析
- 思路一
看到这道题的第一反应就是用归并排序来做,将两个有序的数组首先合并为一个有序的数组,再返回这个有序数组的中位数,就是我们需要得到的结果。
但是,题目中还限制了一条,The overall run time complexity should be O(log (m+n)). 合并排序实现的代码提交时超出了时间限制,为什么会超出呢?我们先来分析一下我们的实现代码的时间复杂度
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
Key = []
i = 0
j = 0
length1 = len(nums1)
length2 = len(nums2)
while (i < length1 and j < length2):
if nums1[i] <= nums2[j]:
Key.append(nums1[i])
i = i + 1
else:
Key.append(nums2[j])
j = j + 1
while (i < length1):
Key.append(nums1[i])
i = i + 1
while (j < length2):
Key.append(nums2[j])
length = len(Key)
if length % 2 == 0:
return (Key[length // 2] + Key[length // 2 - 1]) / 2
else:
return float(Key[length // 2])
输入的两个数组的长度分别为 m m m和 n n n,我们需要遍历两个数组,所以整体代码的时间复杂度为 O ( m + n ) O(m + n) O(m+n), 这显然不符合题目要求的时间复杂度