a = [29,1,3,2,4,65,456,45,37,98,65,44,76,1233,435,6657,345325,34523,6545,3334,556]
b = set(a)
import time
t1 = time.time()
if 3 in a:
print('true')
t2 = time.time()
t3 = time.time()
if 3 in b:
print('true')
t4 = time.time()
delta1 = int(t2*1000000)-int(t1*1000000)
delta2 = int(t4*1000000)-int(t3*1000000)
print('list cost:',delta1,'set cost:', delta2)
> list cost:1219 set cost:219
可以看出同样查找 set 内快很多
leetcode #128(Longest Consecutive Sequence) > Given an unsorted array of integers, find the length of the longest consecutive elements sequence. > Your algorithm should run in O(n) complexity. > Example: > Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.