0
点赞
收藏
分享

微信扫一扫

【Leetcode】数据结构-二分法-4


题目:

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

输入输出:

输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2

解题思路:

方法一:合并为同一个数组,排序,查找中位数

方法二:

算法实现:

方法一:

class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
num = nums1 + nums2
num = sorted(num)
l = len(num)
if l%2 == 0:
return (num[l//2]+num[l//2-1])/2
else:
return num[l//2]

方法二:

 

 

 

出现问题:

1. // 和 / 的区别

2. leetcode 中的Python应该是Python2用Python3应该自己选Python3

没考虑到的问题:

 

举报

相关推荐

0 条评论