Python
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dictionary = {}
for num in nums[1:]:
if nums[0] == num or num in dictionary:
return True
dictionary[num] = 0
return False
Here we basically create “empty” keys in the dictionary to allow accessing previously seen elements much faster. More on how this works can be found in Hashtables and Hashmaps and Hashsets. Later I found out that Hashsets are a thing and implemented them here:
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
hash_set = set()
for num in nums[1:]:
if nums[0] == num or num in hash_set:
return True
hash_set.add(num)
return False
Later one when checking the best performing solutions I found this which uses the ability if a set()
function which eliminates all duplicates, very elegant indeed!
class Solution(object): def containsDuplicate(self, nums):
if len(nums) > len(set(nums)):
return True
return False
Since it’s Python all of the solutions above perform roughly the same and it’s mostly based on luck. Performance swings between 410 and 440 ms.