美文网首页
2020-02-26 Day4 Leetcode:4. Medi

2020-02-26 Day4 Leetcode:4. Medi

作者: YueTan | 来源:发表于2020-02-26 08:09 被阅读0次

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)).

You may assume nums1 and nums2 cannot be both empty.


class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        
        result=[]
        i,j=0,0
        while i<len(nums1) and j<len(nums2):
            if nums1[i]<nums2[j]:
                result.append(nums1[i])
                i+=1
            else:
                result.append(nums2[j])
                j+=1
        while i<len(nums1):
            result.append(nums1[i])
            i+=1
        while j<len(nums2):
            result.append(nums2[j])
            j+=1
        
        if len(result)%2==1:
            return result[len(result)//2]
        else:
            return (result[len(result)//2]+result[len(result)//2-1])/2
        
                
        

相关文章

网友评论

      本文标题:2020-02-26 Day4 Leetcode:4. Medi

      本文链接:https://www.haomeiwen.com/subject/ivypchtx.html