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
            
    

      



  • 相关阅读:
    安装Hive2及配置HiveSever2
    sqoop语句
    Sqoop配置
    IO流的概述
    List集合的简单使用
    包装类
    访问权限修饰符
    接口
    抽象类
    final关键字
  • 原文地址:https://www.cnblogs.com/jiandanqinxin/p/8621324.html
Copyright © 2011-2022 走看看