Leetcode: Contains duplicate
Given an array of nums, return True if there is a duplicated number and False otherwise.
The simple most solution I could find was to use a set and then see for every number if it is already contained in the set. A map would have worked as well. The time complexity for this is O(n), assuming that the access to the hash set is O(1), it takes only one iteration over the whole list.
from typing import List, Optional
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
s = set()
for n in nums:
if n in s:
return True
s.add(n)
return False
if __name__ == '__main__':
s = Solution().containsDuplicate
print(s([1,2,3,1]), True)
print(s([1,2,3,4]), False)
print(s([1,1,1,3,3,4,3,2,4,2]), True)