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?
def containsDuplicate( nums):
if len(nums) < 2:
return False
cnt = 0
flag = False
length = len(nums)
while cnt < length:
p = cnt + 1
while p < length:
if nums[cnt] == nums[p]:
flag = True
break
p += 1
cnt += 1
return flag
Advertisement
Answer
You could use a set:
>>> lst = [1, 2, 3] >>> len(set(lst)) != len(lst) False >>> lst = [1, 2, 2] >>> len(set(lst)) != len(lst) True
EDIT: a faster version, as pointed out in the comments:
>>> lst = [3] + list(range(10**4)) >>> seen = set() >>> any(x in seen or seen.add(x) for x in lst) True >>> seen set([0, 1, 2, 3])