# 217. Contains Duplicate 存在重复元素

@TOC

[LeetCode]

Total Accepted: 86528 Total Submissions: 209877 Difficulty: Easy

## # 题目描述

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.

Example 1:

``````Input: [1,2,3,1]
Output: true
``````

Example 2:

``````Input: [1,2,3,4]
Output: false
``````

Example 3:

``````Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
``````

## # 解题方法

### # 字典统计词频

``````public class Solution {
public boolean containsDuplicate(int[] nums) {
HashMap map = new HashMap();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
return true;
} else {
map.put(nums[i], nums[i]);
}
}
return false;
}
}
``````

AC:17ms

python版本：

``````class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums: return False
count = collections.Counter(nums)
return count.most_common(1)[0][1] > 1
``````

### # 使用set

``````public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set=new HashSet();
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
return true;
} else {
}
}
return false;
}
}
``````

AC:16ms

python版本：

``````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
"""
if not nums: return False
nums.sort()
return any(nums[x] - nums[x + 1] == 0 for x in xrange(len(nums) - 1))
``````

## # 日期

2016/5/1 10:55:17 2018 年 11 月 13 日 —— 时间有点快