一、题目描述
题目原文:
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)).
(两个长度分别为m和n的有序数字列表,请找出两个列表拼接后的中位数。时间复杂度要在O(log (m+n))内完成)
举例:
Example1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
注意:
最终输出为小数的形式。
二、题目分析
思路:
我的思路比较简单,就是新建一个m+n长的列表,将原来两个列表数字整合并排序存入,找下标的中间位置即可。
并判断长度为奇数或者偶数,在进行不同的操作,并将结果转化为小数形式。
三、Python代码
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ #创建新列表,并整合两个输入列表,之后进行排序 nums3 = [] nums3.extend(nums1) nums3.extend(nums2) nums3.sort() #判断nums3的长度为奇数还是偶数并进行取中位数的操作 if len(nums3) & 1 == 1: return nums3[(len(nums3) - 1) / 2] else: if (nums3[len(nums3) / 2] + nums3[len(nums3) / 2 - 1]) & 1 == 1: return float(nums3[len(nums3) / 2] + nums3[len(nums3) / 2 - 1]) / 2 else: return (nums3[len(nums3) / 2] + nums3[len(nums3) / 2 - 1]) / 2 #注意:1、我没有将len(nums3)赋值给一个中间变量,导致代码看起来是很乱的。原因:这样的代码减少了Runtime。 # 若复制给中间变量,则会增加Runtime。 # 2、奇偶判断,我用 & 1 而不是 % 2,原因:&操作 相比 %操作减少了Runtime。
四、其他
题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/
Runtime: 92 ms
想法不够优化,欢迎大家留言交流~