Leetcode--Binary Search(python)

4. Median of Two Sorted Arrays

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)log(m+n))的時間複雜度,而題目要求O(log(m+n))的時間複雜度。這道題其實考察的是二分查找.
二分查找法找兩個數列的第k小個數:
即程序中getKth(A, B , k)函數的實現。用一個例子來說明這個問題:A = {1,3,5,7};B = {2,4,6,8,9,10};如果要求第7個小的數,A數列的元素個數爲4,B數列的元素個數爲6;k/2 = 7/2 = 3,而A中的第3個數A[2]=5;B中的第3個數B[2]=6;而A[2]<B[2];則A[0],A[1],A[2]中必然不可能有第7個小的數。因爲A[2]<B[2],所以比A[2]小的數最多可能爲A[0], A[1], B[0], B[1]這四個數,也就是說A[2]最多可能是第5個大的數,由於我們要求的是getKth(A, B, 7);現在就變成了求getKth(A’, B, 4);即A’ = {7};B不變,求這兩個數列的第4個小的數,因爲A[0],A[1],A[2]中沒有解,所以我們直接刪掉它們就可以了。這個可以使用遞歸來實現。
注意最後乘0.5的原因是這樣才能得到float類型,如果是/2,會得到整形

class Solution(object):
    def getKth(self, A, B, k):
        lenA = len(A)
        lenB = len(B)
        if lenA > lenB:
            return self.getKth(B, A, k)
        if len(A) == 0:
            return B[k-1]
        if k == 1:
            return min(B[0], A[0])
        
        pa = min(lenA, k/2)
        pb = k - pa
        if A[pa-1] <= B[pb-1]:
            return self.getKth(A[pa:], B, pb)
        else:
            return self.getKth(A, B[pb:], pa)
        
    
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        tmp = len(nums1) + len(nums2)
        if tmp % 2 == 1:
            return self.getKth(nums1, nums2, tmp/2+1)
        else:
            return (self.getKth(nums1, nums2, tmp/2) + self.getKth(nums1, nums2, tmp/2+1)) * 0.5
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章