1. 程式人生 > >leetcode python 001

leetcode python 001

while nbsp () 組成 numpy 一個數 time() and target

給定一個數組,和一個數字target,要求返回和為target的兩個數組成員的下標。

import numpy as np
import time

#### 構造題目 , x數組大小
x=100000
l1=np.random.rand(x)
l2=[round(l*x,5) for l in l1]
w1=np.random.randint(0,x)
w2=np.random.randint(0,x)
while w1==w2:
w2=np.random.randint(0,x)
print(‘答案%s,%s‘%(w1,w2))
target=l2[w1]+l2[w2]
print(‘target %s‘%target)

#### 開始計算
t=time.time()
d={}
for i in range(x):
if l2[i] in d.keys():
print(d[l2[i]],i)
print(l2[d[l2[i]]],l2[i])
break
d[target-l2[i]]=i
t=time.time()-t
print(‘%s 元素用時 %s s‘%(x,t))

leetcode python 001