LeetCode第四题Median of Two Sorted Arrays解法

Posted jiandanqinxin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
        

  








以上是关于LeetCode第四题Median of Two Sorted Arrays解法的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode--median-of-two-sorted-arrays

#Leetcode# 4. Median of Two Sorted Arrays

LeetCode: Median of Two Sorted Arrays

Leetcode 4. Median of Two Sorted Arrays(二分)

LeetCode题解-----Median of Two Sorted Arrays

leetcode-4 Median of Two Sorted Arrays