leetcode-4. Median of Two Sorted Arrays

https://leetcode.com/problems/median-of-two-sorted-arrays/description/

题意理解:二分找中位数,凑《=(m+n+1)/2的在a中的数,然后找到在b中的数

急转弯:先定a,再定b

算法:二分

数据结构:

#
#

'binary'

__author__ = 'hjkruclion'

import sys

def read_int():
    return list(map(int, sys.stdin.readline().split()))

class Solution:
    def b_b(self, m, x, b):
        l = 0
        r = m
        while(l < r):
            mid = (l + r) // 2
            if b[mid] <= x:
                l = mid + 1
            else:
                r = mid
        return r - 1 + 1
    def b_a(self, n, m, key, a, b):
        l = 0
        r = n
        while(l < r):
            mid = (l + r) // 2
            res = mid + 1 + self.b_b(m, a[mid], b)
            if res <= key:
                l = mid + 1
            else:
                r = mid
        return r - 1

    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        a = nums1
        b = nums2
        n = len(a)
        m = len(b)
        key = (n + m + 1) // 2
        x = self.b_a(n, m, key, a, b)
        # print(x)
        num_x = x - 0 + 1
        num_y = key - num_x
        if x < 0:
            L = b[num_y - 1]
        else:
            L = a[x]
            if num_y - 1 >= 0:
                L = max(a[x], b[num_y - 1])
        if (n + m) % 2 == 1:
            return L
        else:
            Ra = x + 1
            Rb = num_y - 1 + 1
            if Ra >= n:
                R = b[Rb]
            elif Rb >= m:
                R = a[Ra]
            else:
                R = min(a[Ra], b[Rb])
            return (L + R) / 2



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值