4_Median_of_Two_Sorted_Arrays.py

来源:互联网 发布:手机网页京东淘宝广告 编辑:程序博客网 时间:2024/04/27 22:04

题目是:

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)).

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

就是求两个数组所有数的的中间值

本来这个问题没什么难度的直接合并排序之后取中值,如下:

    def time_complex_n(self, nums1, nums2):        nums = nums1 + nums2        nums.sort()        index, carry = divmod(len(nums), 2)        if carry == 1:            result = float(nums[index])        else:            result = (nums[index] + nums[index-1])/2.0        return result

但是考虑到题目要求的时间复杂度是O(log (m+n))

同时由于O(log (n))是典型的二分查找算法的时间复杂度, 其核心思想是将一个数据分成2半然后分开的每一半再分成2半依次类推.

因此这里不能简单的使用time_complex_n这个算法.




0 0
原创粉丝点击