代码改变世界

[LeetCode] 4. Median of Two Sorted Arrays_Hard tag: Array, Binary Search

2019-05-10 11:39  Johnson_强生仔仔  阅读(191)  评论(0编辑  收藏  举报

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

这个题目我们可以用O(m + n) , 也就是two pointers去得到medium。

但是我们还可以利用divide and conquer的做法,并且更general 去求nums1,nums2中第k个大的值,然后将总长度是奇数和偶数分开来讨论,即可。

T: O(lg(m + n))

关于求nums1,nums2中第k个大的值,我们去比较nums1[start1 + k//2 - 1], nums2[start2 + k//2 - 1] 的值,如果某一个比较小,表明第k大的肯定不在那个数组的前k//2个,可以将其舍去,有点想二分法,只不过是在两个数组之间进行比较,注意的是如果start1 + k//2 - 1 > length, 那么我们就将其设为maxValue = max(nums1[-1], nums2[-1]) + 1,因为肯定是要舍弃另一个数组中的前k//2个。

Note: In order to get the median when it contains odd length, we should have (num1 + num2)/2.0

code

class Solution:
    def medianTwoArray(self, nums1, nums2):
        def findKth(nums1, start1, nums2, start2, k):
            if start1 >= len(nums1):
                return nums2[start2 + k - 1]
            if start2 >= len(nums2):
                return nums1[start1 + k - 1]
            if k == 1:
                return min(nums1[start1], nums[start2])
            maxValue = max(nums1[-1], nums2[-1]) + 1
            value1 = nums1[start1 + k//2 - 1] if start1 + k//2 - 1 < len(nums1) else maxValue
            value2 = nums2[start2 + k//2 - 1] if start2 + k//2 - 1 < len(nums2) else maxValue
            return findKth(nums1, start1 + k//2, nums2, start2, k - k//2) if value1 < value2 else findKth(nums1, start1, nums2, start2 + k//2, k - k//2)
        total = len(nums1) + len(nums2)
        return findKth(nums1, 0, nums2, 0, total//2 + 1) if total%2 else (findKth(nums1, 0, nums2, 0, total//2) + findKth(nums1, 0, nums2, 0, total//2 + 1 ))/2.0