Stay button (leetcode 4) Looking for a median of two ordered array of python

topic

Given two ordered arrays of size and nums1 m and n nums2.

Please find both the median and orderly array, and requires time complexity of the algorithm is O (log (m + n)).

You can not assume nums1 and nums2 both empty.

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3) / 2 = 2.5

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/median-of-two-sorted-arrays

Thinking

Read a lot of blog, I feel this is best understood
https://zhuanlan.zhihu.com/p/39129143

Code

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        m,n=len(nums1),len(nums2)
        if m>n:
            nums1,nums2,m,n=nums2,nums1,n,m
        l,r,num=0,m,(n+m+1)//2
        while l<=r:
            midm=(l+r)//2
            #print(midm)
            midn=num-midm
            if midm>0 and nums1[midm-1]>nums2[midn]:
                r=midm-1
            elif midm<m and nums2[midn-1]>nums1[midm]:
                l=midm+1
            else:
                if midm==0:
                    l_max=nums2[midn-1]
                elif midn==0:
                    l_max=nums1[midm-1]
                else: 
                    l_max=max(nums2[midn-1],nums1[midm-1])
                
                if (m+n)%2==1:
                   return l_max
                if midm==m:
                    r_min=nums2[midn]
                elif midn==n:
                    r_min=nums1[midm]
                else:
                    r_min=min(nums2[midn],nums1[midm])
                return (l_max+r_min)/2
            

Guess you like

Origin blog.csdn.net/qq_41318002/article/details/93506667