Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

set会消去重复的item。

例如:>>> nums=[1,2,3,2,5]

>>>set(nums)

set([1, 2, 3, 5])

如果去重后的长度与原长度不等,则说明里面有重复的数字。

class Solution(object):
def containsDuplicate(self, nums):
    """
    :type nums: List[int]
    :rtype: bool
    """
    return len(nums) != len(set(nums))
class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        charset = set()
        for item in nums:
            if item in charset:
                return True
            else:
                charset.add(item)
        return False

Alistkeeps order,dictandsetdon't: when you care about order, therefore, you must uselist(if your choice of containers is limited to these three, of course;-).

dictassociates with each key a value, whilelistandsetjust contain values: very different use cases, obviously.

setrequires items to be hashable,listdoesn't: if you have non-hashable items, therefore, you cannot usesetand must instead uselist.

setforbids duplicates,listdoes not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found incollections.Counter-- you could build one as adict, if for some weird reason you couldn't importcollections, or, in pre-2.7 Python as acollections.defaultdict(int), using the items as keys and the associated value as the count).

Checking for membership of a value in aset(ordict, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking,setis better thanlist.

Last updated

Was this helpful?