217. contains duplicate

Question

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.

Analysis

简单的用HashSet 去重复,add method O(1), contains method O(1).

Complexity

Time: O(n)

Solution

1
2
3
4
5
6
7
8
9
10
11
public boolean (int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int n : nums) {
if (set.contains(n)) {
return true;
} else {
set.add(n);
}
}
return false;
}