zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    团队项目的NABC(截图软件)
    《梦断代码》读后感_3
    《梦断代码》读后感_2
    毕设今日总结(二)
    毕业设计今日总结(一)
    QT中文乱码解决方法
    课堂练习——最大联通之数组
    《浪潮之巅》读书笔记3
    《浪潮之巅》读书笔记2
    《浪潮之巅》读书笔记1
  • 原文地址:https://www.cnblogs.com/alfredsun/p/10773015.html
Copyright © 2011-2022 走看看