05 August 2008
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:
1
2
Input: [1,2,3,1]
Output: true
Example 2:
1
2
Input: [1,2,3,4]
Output: false
Example 3:
1
2
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
判断数组是否包含有任意元素的重复元素,如果包含返回true;可以先排序然后比较相邻元素,也可以使用HashMap来检查,如果元素不存在,放入HashMap中,如果存在,返回false。要时间还是要空间。
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public boolean containsDuplicate(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
return true;
} else {
map.put(num, 1);
}
}
return false;
}
}
Hashset
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length < 2) {
return false;
}
HashSet<Integer> noDup = new HashSet<>();
for (int num : nums) {
if (!noDup.add(num)) {
return true;
}
}
return false;
}
}