[leetcode]4. Median of Two Sorted Arrays

  开始以为是求m n的中位数然后再求平均数,

  被-2 -1 和 3 打脸

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        # ---
        # deal NULL
        if len(nums1) == 0:
            return self.median(nums2)   #NULL no need to devide
        if len(nums2) == 0:
            return self.median(nums1)
        # ---
        # deal 0
        if nums1 == [0]:
            return self.median(nums2) /2    #0 need to devide
        if nums2 == [0]:
            return self.median(nums1) /2
        # ---
        # normal
        return (self.median(nums1) + self.median(nums2)) / 2

    def median(self, string) -> float:
        if (len(string) % 2) == 1:
            # odd number
            return string[len(string) // 2] /1.0
        else:
            # even number
            return (string[len(string) // 2] + string[len(string) // 2 - 1]) / 2

 

无耻的用下list.srot()轻松通过(内存还是惨不忍睹

 

Runtime: 60 ms, faster than 96.75% of Python3 online submissions for Median of Two Sorted Arrays.
Memory Usage: 13.5 MB, less than 5.11% of Python3 online submissions for Median of Two Sorted Arrays.
 
class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        # ---
        # deal NULL
        if len(nums1) == 0:
            return self.median(nums2)  # NULL no need to devide
        if len(nums2) == 0:
            return self.median(nums1)
        # ---
        # normal
        sum = nums1 + nums2
        sum.sort()
        return self.median(sum)

    def median(self, string) -> float:
        if (len(string) % 2) == 1:
            # odd number
            return string[len(string) // 2] / 1.0
        else:
            # even number
            return (string[len(string) // 2] + string[len(string) // 2 - 1]) / 2.0

 

posted @ 2019-04-26 10:49  夜歌乘年少  阅读(219)  评论(1编辑  收藏  举报