um trying to check whether there are duplicate values exists in an integer list by python . this was successful and I found that the execution time getting higher when the size of the list getting increase. How may I improve the run time of the following logic?
JavaScript
x
16
16
1
def containsDuplicate( nums):
2
if len(nums) < 2:
3
return False
4
cnt = 0
5
flag = False
6
length = len(nums)
7
while cnt < length:
8
p = cnt + 1
9
while p < length:
10
if nums[cnt] == nums[p]:
11
flag = True
12
break
13
p += 1
14
cnt += 1
15
return flag
16
Advertisement
Answer
You could use a set:
JavaScript
1
7
1
>>> lst = [1, 2, 3]
2
>>> len(set(lst)) != len(lst)
3
False
4
>>> lst = [1, 2, 2]
5
>>> len(set(lst)) != len(lst)
6
True
7
EDIT: a faster version, as pointed out in the comments:
JavaScript
1
7
1
>>> lst = [3] + list(range(10**4))
2
>>> seen = set()
3
>>> any(x in seen or seen.add(x) for x in lst)
4
True
5
>>> seen
6
set([0, 1, 2, 3])
7