标签:int ott close 代码量 不能 .so interview 题目 pen
一、题目
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 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
#coding:utf-8 class Solution0: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ newnum = [None]*(len(nums1)+len(nums2)) if nums1 == None or nums2 == None: return nums1_point = len(nums1)-1 nums2_point = len(nums2)-1 new_point = len(nums1)+len(nums2)-1 while nums1_point >= 0 and nums2_point >= 0: if num1[nums1_point] > num2[nums2_point]: newnum[new_point] = nums1[nums1_point] new_point-=1;nums1_point-=1 else: newnum[new_point] = nums2[nums2_point] new_point -=1;nums2_point-=1 while nums1_point >= 0: newnum[new_point] = nums1[nums1_point] new_point-=1;nums1_point-=1 while nums2_point >= 0: newnum[new_point] = nums2[nums2_point] new_point-=1;nums2_point-=1 print(newnum) if len(newnum) % 2 != 0: median = newnum[len(newnum)//2] else: median = (newnum[len(newnum)//2-1] + newnum[(len(newnum)//2)])/2 print(median) return median
class Solution1:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
for i in nums2:
nums1.append(i)
nums1.sort()
k=len(nums1)
if k%2==0:
return (float(nums1[int(k/2-1)])+nums1[int(k/2)])/2
else:
return nums1[int((k-1)/2)]
class Solution2:
def getKth(self,A,B,k):
lenA = len(A);lenB = len(B)
if lenA > lenB: return self.getKth(B,A,k)
if lenA == 0: return B[k-1]
if k == 1: return min(A[0],B[0])
pa = min(k//2,lenA);pb = k - pa
if A[pa-1] <= B[pb-1]:
return self.getKth(A[pa:],B,pb)
else:
return self.getKth(A,B[pb:],pa)
def findMedianSortedArrays(self,A,B):
lenA = len(A);lenB = len(B)
if (lenA + lenB) % 2 == 1:
print(self.getKth(A,B,(lenA+lenB)//2 + 1))
return self.getKth(A,B,(lenA+lenB)//2 + 1)
else:
print((self.getKth(A,B,(lenA+lenB)//2) + self.getKth(A,B,(lenA+lenB)//2+1))*0.5)
return (self.getKth(A,B,(lenA+lenB)//2) + self.getKth(A,B,(lenA+lenB)//2+1))*0.5
if __name__ == ‘__main__‘: num1 = [1,2,8] num2 = [4,5,6,7,10] ss =Solution0() ss.findMedianSortedArrays(num1,num2)
参考博客:https://blog.csdn.net/suibianshen2012/article/details/51842597 https://www.cnblogs.com/zuoyuan/p/3759682.html http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
LeetCode Hard: 4. Median of Two Sorted Arrays
标签:int ott close 代码量 不能 .so interview 题目 pen
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/9017833.html