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
原文地址:https://www.cnblogs.com/jiandanqinxin/p/8621324.html
时间: 2024-10-11 03:52:25