继续写leetcode啦,既上次发现了Counter函数之后,又发现了用武之地啦。这次的题目简直就是撞枪口了。检查是否有重复数。太简单啦。代码如下:
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
from collections import Counter
c = Counter(nums)
for i in c.keys():
if c[i] > 1:
return True
else:
return False
洗澡的时候想起来一种更简单的方法,用了以后果然更快了。就是用set的自动消除重复的特点
<pre name="code" class="python">class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(set(nums)) != len(nums):
return True
else:
return False