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:

  1. Duplicates: set automatically removes duplicates, while list allows duplicates.
  2. Order: list preserves the order of elements, while set does not guarantee the order of elements.
  3. Indexing: list supports indexing, while set does not.
  4. Mutability: Both list and set are mutable (can be changed), but the methods available to change each are different.
  5. Membership testing: Both list and set 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.