4. 寻找两个有序数组的中位数

 


class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        length=len(nums1)+len(nums2)
        mid=0;tmp1=0;tmp2=0
        mid=length//2+1
        i=0;j=0
        while mid>0:        
            if i<len(nums1) and j< len(nums2):
                if nums1[i]<nums2[j]:
                    tmp2=tmp1
                    tmp1=nums1[i];i+=1
                else:
                    tmp2=tmp1
                    tmp1=nums2[j];j+=1
            elif i<len(nums1):
                tmp2=tmp1
                tmp1= nums1[i];i+=1
            else:
                tmp2=tmp1
                tmp1=nums2[j];j+=1
            mid-=1
        if length&1 == 1:
            return tmp1
        else:
            return (tmp1+tmp2)/2


s=Solution()
print(s.findMedianSortedArrays([2,4],[1,7]))

 

posted @ 2019-02-26 20:18  小饭勺  阅读(165)  评论(0)    收藏  举报