题目内容
给定两个大小为 m 和 n 的有序数组 nums1
和 nums2
。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1
和 nums2
不会同时为空。
https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
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
题目思路
一种比较好想的思路就是我把两个字符串合体成一个,然后直接输出。不过另一种方式就是进行比对排序,因为两个序列都是已经排序好的。先确定要找的是第几个数字即可。因为上来就排序的话,其实中位值之后的是不需要排序的,造成了浪费。但是后来我看了一下,使用第一种方法的速度要远快于第二种,晕菜。。
程序代码
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
l1,l2=len(nums1),len(nums2)
length=l1+l2
flag=1
if length%2==0:#是偶数
flag=2
find=length//2+1
res=[]
while nums1 or nums2:
if nums1 and nums2:
if nums1[0]<=nums2[0]:
res.append(nums1.pop(0))
else:
res.append(nums2.pop(0))
elif nums1:
res.extend(nums1)
break
elif nums2:
res.extend(nums2)
break
if len(res)==find:
break
if flag==1:
return res[length//2]
else:
return (res[length//2]+res[length//2-1])/2.0