Contains Duplicate
Problem information
- Leedcode problem: https://leetcode.coqm/problems/contains-duplicate/
- Neetcode problem: https://neetcode.io/problems/duplicate-integer
- Difficulty: Easy
Solution
Use a HashSet to insert and check if the set contains a given number in constant time.
- Time Complexity:
O(n) - Space Complexity:
O(n)
class Solution {
public boolean hasDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num: nums) {
if (set.contains(num)) {
return true;
}
set.add(num);
}
return false;
}
}