動態

詳情 返回 返回

二分查找--尋找兩個正序數組的中位數 - 動態 詳情

leetcode鏈接:https://leetcode.cn/problems/median-of-two-sorted-arrays/desc...

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        """
    找出兩個已經排序的數組的中位數
    解法思路:二分查找
    中位數:找有序數組中間的數字,假設中位數是第k個數,即尋找第k個數,那麼就取 pivot1 = nums1[k/2-1] 和 pivot2 = nums2[k/2-1]
    每次取pivot1和pivot2中較小的那個,然後比較pivot1和pivot2的大小
    pivot1 > pivot2,説明nums1[0 .. k/2-1]都不可能是中位數,因為nums1[0 .. k/2-1]中的最大值都小於pivot2,所以可以排除nums1[0 .. k/2-1]
    pivot1 < pivot2,説明nums2[0 .. k/2-1]都不可能是中位數,因為nums2[0 .. k/2-1]中的最大值都小於pivot1,所以可以排除nums2[0 .. k/2-1]
    每次排除掉了一部分元素,所以從k中刪除掉排除的元素個數
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: float
    """
        def getKNumber(k):
            index1 = index2 = 0
            while True:
                if index1 == len(nums1):     # 第k個數不可能在nums1數組當中
                    return nums2[index2 + k - 1]
                if index2 == len(nums2):
                    return nums1[index1 + k - 1]
                if k == 1:
                    return min(nums1[index1], nums2[index2])

                # 按照index1,index2為起點,不斷通過二分查找更新,縮小範圍
                newIndex1 = min(index1 + k // 2 - 1, len(nums1) - 1)
                newIndex2 = min(index2 + k // 2 - 1, len(nums2) - 1)

                pivot1, pivot2 = nums1[newIndex1], nums2[newIndex2]
                if pivot1 <= pivot2:
                    k -= newIndex1 - index1 + 1
                    index1 = newIndex1 + 1
                else:
                    k -= newIndex2 - index2 + 1
                    index2 = newIndex2 + 1

        total_length = len(nums1) + len(nums2)
        if total_length % 2 == 1: # 如果為奇數個元素,取中間元素即可
            return getKNumber(total_length // 2 + 1)
        else:
            return getKNumber(total_length // 2) / 2 + getKNumber(total_length // 2 + 1) / 2

Add a new 評論

Some HTML is okay.