美文网首页
LeetCode 4.Median of Two Sorted

LeetCode 4.Median of Two Sorted

作者: 费城的二鹏 | 来源:发表于2018-11-22 12:35 被阅读8次

Median of Two Sorted Arrays

写晕了,但是 AC 了。

因为题目要求的时间复杂度,O(log (m+n)). 主要思想就是二分法,先二分数组1,放入数组2判断是否符合中位数条件,如果不符合就依据条件继续二分。奇偶情况需要分别处理。

class Solution:

    def cal(self, s1, mid, s2, index):
        length = len(s1) + len(s2)
        if length % 2 == 1:
            return s1[mid]
        
        minNum = -1
        if mid < len(s1) - 1 and index < len(s2):
            minNum = min(s1[mid + 1], s2[index])
        elif mid < len(s1) - 1:
            minNum = s1[mid + 1]
        elif index < len(s2):
            minNum = s2[index]

        return 1.0 * (s1[mid] + minNum) / 2

    def binary(self, s1, s2):
        left = 0
        right = len(s1)
        const_left = (len(s1) + len(s2) - 1) >> 1
        while left < right:
            mid = (left + right) >> 1
            index = const_left - mid
            if index < 0:
                right = mid
            elif index > len(s2):
                left = mid + 1
            else:
                if index == 0:
                    if index < len(s2) and s2[index] >= s1[mid]:
                        return (True, self.cal(s1, mid, s2, index))
                    else:
                        right = mid
                elif index == len(s2):
                    if index - 1 >= 0 and s2[index - 1] <= s1[mid]:
                        return (True, self.cal(s1, mid, s2, index))
                    else:
                        left = mid + 1
                else:
                    if s2[index - 1] <= s1[mid] and s2[index] >= s1[mid]:
                        return (True, self.cal(s1, mid, s2, index))
                    elif s2[index] < s1[mid]:
                        right = mid
                    else:
                        left = mid + 1
        return (False, 0)

    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """

        if len(nums1) == 0 or len(nums2) == 0:
            length = len(nums1)
            if length == 0:
                nums1 = nums2
                length = len(nums1)
            if length % 2 == 1:
                print(nums1[length >> 1])
                return nums1[length >> 1]
            index = length >> 1
            print(1.0 * (nums1[index - 1] + nums1[index]) / 2)
            return 1.0 * (nums1[index - 1] + nums1[index]) / 2

        (success, value) = self.binary(nums1, nums2)
        if not success:
            (success, value) = self.binary(nums2, nums1)
        
        print(value)
        return value

相关文章

网友评论

      本文标题:LeetCode 4.Median of Two Sorted

      本文链接:https://www.haomeiwen.com/subject/nuflqqtx.html