zoukankan      html  css  js  c++  java
  • LeetCode第四题Median of Two Sorted Arrays解法

    There are two sorted arrays nums1 and nums2 of size m and n respectively.

    Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

    example:

    nums1 = [1, 3]
    nums2 = [2]
    The median is 2.0

    简单来说,这道题的要求就是求两个数组的中位数,因为最近一直在学习Python,所以给大家展现下我自己的想法,希望大家互相交流。
     
    class Solution:
        def findMedianSortedArrays(self, nums1, nums2):
            #连接两个数组
            nums3 = nums1 + nums2
            #数组排序
            nums3.sort()
            #初始化中位数的值为0
            med = 0
            index = index1 = index2 = 0
            lenofnums = len(nums3)
            if((lenofnums % 2) == 0):
                #如果为偶数个则取中间两个数的平均值
                index1 = int(lenofnums / 2 - 1)
                index2 = int(index1 + 1)
                med = (nums3[index1] + nums3[index2]) / 2
            else:
                #如果为奇数个直接取中间值
                index = int((lenofnums + 1) / 2 - 1)
                med = nums3[index]
            return med
            
    

      



  • 相关阅读:
    一周的前端面试
    PHP导出超大的CSV格式的Excel表方案
    Java HashMap Demo
    Vmware 设置桥接模式
    Vue 模板
    SpringMVC 拦截器
    IntelliJ IDEA 修改缓存文件设置
    Maven 命令操作项目
    Maven 介绍
    Spring Boot 5 SpringSecurity身份验证
  • 原文地址:https://www.cnblogs.com/jiandanqinxin/p/8621324.html
Copyright © 2011-2022 走看看