码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode第四题Median of Two Sorted Arrays解法

时间:2018-03-22 10:56:57      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:family   个数   body   中位数   spec   solution   self   16px   mil   

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
        

  



LeetCode第四题Median of Two Sorted Arrays解法

标签:family   个数   body   中位数   spec   solution   self   16px   mil   

原文地址:https://www.cnblogs.com/jiandanqinxin/p/8621324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!