leetcode -- Median of Two Sorted Arrays -- 重点有技巧

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

看这里提供的思路
http://yucoding.blogspot.hk/2013/01/leetcode-question-50-median-of-two.html

http://www.cnblogs.com/zuoyuan/p/3759682.html

http://chaoren.is-programmer.com/posts/42890.html

class Solution(object):

    def fms(self, A, B, k):#找A与B的数组集合中第k小的数
        if len(A) > len(B):#这里默认len(A) < len(B)
            return self.fms(B, A, k)
        else:
            if len(A) == 0:
                return B[k-1]
            if k == 1:
                return min(A[0], B[0])
            pa = min(k/2, len(A))
            pb = k - pa# 即len(pa) + len(pb) == k, 即A和B总共挑k个数出来
            if A[pa-1] <= B[pb-1]:#看ref的解释
                return self.fms(A[pa::], B, k-pa)
                #return self.fms(A[pa:], B, k-pa)也可以
            else:
                return self.fms(A, B[pb::], k-pb)

    def findMedianSortedArrays(self, nums1, nums2):
        """ :type nums1: List[int] :type nums2: List[int] :rtype: float """
        if (len(nums1) + len(nums2))%2 == 0:
            return (self.fms(nums1, nums2, (len(nums1) + len(nums2))/2) + self.fms(nums1, nums2, (len(nums1) + len(nums2))/2 + 1))/2.0
        else:
            return self.fms(nums1, nums2, (len(nums1) + len(nums2))/2 + 1)

你可能感兴趣的:(LeetCode)