LeetCode-Median of Two Sorted Arrays

来源:互联网 发布:淡雅的名字 知乎 编辑:程序博客网 时间:2024/06/05 07:22

原题

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

注意点:

  • 数组是有序的
  • 时间复杂度为O(log (m+n))
  • 考虑奇偶情况,如果总是为偶数,应返回中间的两个数的平均数,且为float类型

  • Python版本问题,部分Python3语法LeetCode好像不支持。

解题思路

     整体思路类似于在一个无序数组内找最小的D第k个数。我们通过两个数组各自的中位数将两个数组A、B分为四个部分,分别为A1、A2、B1、B2。现在我们来找出他们中第k小的数。

     1)如果A的中位数比B的中位数大,那么B1中的数比A2和B2中的都小,且小于部分A1中的数。且A2中的数比A1和B1的大,且比部分B2的大,此时,a)如果k>len(A1)+len(B1),那么第k个数就不可能在B1,因为比B1的数小的数最多只有B1加上部分的A1,也就是k<len(A1)+len(B1),矛盾;b)如果k<=len(A1)+len(B1),那么第k个数就不可能在A2中,因为A2中的数至少比A1加B1中的数大,也就是k>len(A1)+len(B1),矛盾。同理可以推理出另外两种情况。

Code

# -*- coding: utf-8 -*-__author__ = 'tongbao'class Solution(object):    def findMedianSortedArrays(self,nums1,nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: float        """        length1 = len(nums1)        length2 = len(nums2)        k = (length1+length2) // 2        if (length1 + length2) % 2 == 0:            return (self.findK(nums1,nums2,k) + self.findK(nums1,nums2,k - 1)) / 2.0        else:            return self.findK(nums1,nums2,k)    def findK(self,num1,num2,k):        if not num1:            return num2[k]        if not num2:            return num2        if k == 0:            return min(num1[0],num2[0])        length1 = len(num1)        length2 = len(num2)        if num1[length1 // 2] > num2[length2 // 2]:            if k > length1 //2 + length2 // 2:                return self.findK(num1,num2[length2 // 2 + 1:],k - length2 // 2 - 1)            #因为B1中的所有数已经确定比目标数小了,即已经排除了length2个最小的数,接下来的数据集中继续查找第k - length2 // 2 - 1个小的数。            else:                return self.findK(num1[:length1 // 2],num2,k)            # 第k个小的数不包括在A2中,在接下来的数据集中继续查找第k 个小的数。        else:            if k > length1 // 2 + length2 // 2:                return self.findK(num1[length1 // 2 + 1:],num2,k - length1 //2 -1)            else:                return self.findK(num1,num2[:length2],k)if __name__ == "__main__":    assert Solution().findMedianSortedArrays([2, 4,6], [1, 2, 3,4]) == 3    assert Solution().findMedianSortedArrays([], [4, 6]) == 5
 
原创粉丝点击