Contain Duplicate
easy desciption accept solution:
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
unique = set()
for i in nums:
if i in unique:
return True
unique.add(i)
return False
failed solution:
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
unique = []
for item in nums:
if item not in unique:
unique.append(item)
if len(unique) < len(nums):
return True
else:
return False
why? set is faster than list, it can find thing pin point, without search.
the
if len(unique) < len(nums):
return True
else:
return False
here did another search, slowed down the program a lot.
set
and list
are both data structures in Python, but they have some key differences:
- Duplicates:
set
automatically removes duplicates, whilelist
allows duplicates. - Order:
list
preserves the order of elements, whileset
does not guarantee the order of elements. - Indexing:
list
supports indexing, whileset
does not. - Mutability: Both
list
andset
are mutable (can be changed), but the methods available to change each are different. - Membership testing: Both
list
andset
allow you to check if an item is in the collection, but sets provide a faster way of checking for membership due to the hash table implementation.
In general, you would use a list
when you need to preserve order and potentially have duplicates, while you would use a set
when you want to eliminate duplicates and do not care about the order of elements.