1. 程式人生 > >leetcode python 004

leetcode python 004

list n) 中位數 pytho turn leet def bsp 尋找

## 已知l1,l2均為升序數組,
## 在兩數組l1,l2中尋找第n位數,
## 兩數組中位數中,前者大於後者,說明後者中位數以下的成員必定在真正中位數之下
## 可以將其剔除,剔除a個元素後的兩數組中尋找第n-a位數,等價於
def findmid(l1,l2):
m,n=len(l1),len(l2)
if (m+n)%2==0:
return (listrec(l1,l2,(m+n)/2)+listrec(l1,l2,(m+n)/2))/2
else:
return listrec(l1,l2,(m+n+1)/2)
## la長度大於等於lb
def listrec(la,lb,i):
m,n=len(la),len(lb)
if n==0:
return la[i-1]
if m<n:
return listrec(lb,la,i)
if i==1:
return min(la[0],lb[0])
p=min(int(i/2),n)
print(m,n,i,p)
if la[p-1]>lb[-1]:
return listrec(la,lb[p:],i-p)
else:
return listrec(la[p:],lb,i-p)

lm=[x for x in range(13,200)if x%2==0]
ln=[x for x in range(15,99)if x%2==1]
print(findmid(lm,ln))

leetcode python 004