题目描述
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
样例描述
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
思路
- 暴力做法:先排序,然后逐个相邻比较是否有重复元素,比较简单不给代码
- 哈希做法:
HashSet
有自动去重功能,如果里面已经有某个元素,再次添加时会返回null
,利用这个特点即可
代码
class Solution {
public boolean containsDuplicate(int[] nums) {
//哈希表来做
Set<Integer> set = new HashSet<>();
for (int x: nums){
if (!set.add(x)){
return true;
}
}
return false;
}
}