There is sorted arrays nums1 and nums2 of size m and N respectively.
Find The median of the sorted arrays. The overall run time complexity should be O (log (m+n)).
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
classsolution (object):deffindmediansortedarrays (self, NUMS1, NUMS2):""": Type Nums1:list[int]: type Nums2:list[int]: rtype:float""" while1: ifLen (nums1) +len (NUMS2) <= 2: ifLen (nums1) = =0:res= Float (nums2[0]+nums2[-1])/2elifLen (nums2) = =0:res= Float (nums1[0]+nums1[-1])/2Else: Res= Float (nums1[0]+nums2[0])/2 Break; ifLen (nums1) = =0:ifLen (NUMS2) > 2: delNums2[0]delNums2[-1] elifLen (NUMS2) > 1: Res= Float (nums2[0]+nums2[-1])/2 Break Else: Res=Nums2[0] Break; elifLen (nums2) = =0:ifLen (NUMS1) > 2: delNums1[0]delNums1[-1] elifLen (NUMS1) > 1: Res= Float (nums1[0]+nums1[-1])/2 Break; Else: Res=Nums1[0] Break; Else: ifNums1[0] <Nums2[0]:delNums1[0]elifNums1[0] >Nums2[0]:delNums2[0]Else: ifLen (NUMS1) >Len (NUMS2):delNums1[0]Else: delNums2[0]ifLen (nums1) = =0:delNums2[-1] elifLen (nums2) = =0:delNums1[-1] Else: ifNums1[-1] > Nums2[-1]: delNums1[-1] elifNums1[-1] < Nums2[-1]: delNums2[-1] Else: ifLen (NUMS1) >Len (NUMS2):delNums1[-1] Else: delNums2[-1] returnFloat (RES)
The idea is to delete each of the two lists in one of the smallest and one of the largest, and the last remaining number or two-digit mean is the value to return.
But to judge the situation too much, the code is too smelly and long, look at the comment area is not particularly pleasing to the eye, so it.
Feel the next problem is not ashamed to send ...
Python language, Leetcode exam questions record (iv) Median of the Sorted Arrays