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])
如果去重后的长度与原长度不等,则说明里面有重复的数字。
Alist
keeps order,dict
andset
don't: when you care about order, therefore, you must uselist
(if your choice of containers is limited to these three, of course;-).
dict
associates with each key a value, whilelist
andset
just contain values: very different use cases, obviously.
set
requires items to be hashable,list
doesn't: if you have non-hashable items, therefore, you cannot useset
and must instead uselist
.
set
forbids duplicates,list
does 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,set
is better thanlist
.
Last updated
Was this helpful?