Use a HashSet
to detect duplicates.
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet();
for (int num : nums) {
if (set.contains(num)) {
return true;
}
set.add(num);
}
return false;
}
}
- Time Complexity: O(n)
- Space Complexity: O(n)