zoukankan      html  css  js  c++  java
  • LeetCode 阶段二

    ( leetcode 4 ) 二分法查找两个有序数组的中位数
    注释:python2和python3除号的处理不同,python2自动转为int类型,python3保留小数;

      class Solution:
        def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
            n = len(nums1) + len(nums2)
            if n%2 == 1:
                return self.findKth(nums1,nums2,int(n/2+1))
            else:
                smaller = self.findKth(nums1,nums2,n/2)
                bigger = self.findKth(nums1,nums2,n/2+1)
                return (smaller + bigger)/2.0
            
        def findKth(self,A,B,k):
            k = int(k)
            if len(A) == 0:
                return B[k-1]
            if len(B) == 0:
                return A[k-1]
            if k == 1:
                return min(A[0],B[0])
            
            a = A[int(k/2)-1] if len(A) >= k/2 else None
            b = B[int(k/2)-1] if len(B) >= k/2 else None
            if b is None or (a is not None and a<b):
                return self.findKth(A[int(k/2):],B[:int(k/2)+1],k-int(k/2))
            return self.findKth(A[:int(k/2)+1],B[int(k/2):],k-int(k/2))
    
  • 相关阅读:
    05 css继承性
    04 选择器权重
    03 css三种引入的方式
    02 css实现举例
    01 css介绍
    05 dl-添加定义列表
    04 ol-热门点击排行榜
    02 h1 p hr br 特殊符号
    01html简介
    函数内置方法
  • 原文地址:https://www.cnblogs.com/curtisxiao/p/10978189.html
Copyright © 2011-2022 走看看