Problem
Problem Link
Time Complexity: O(n), Space Complexity: O(n)
class Solution {
public boolean containsDuplicate(int[] nums) {
// Create a HashMap to store the elements of the array.
HashMap<Integer, Integer> map = new HashMap<>();
// Traverse all elements in the array.
for (int temp : nums) {
// Check if the current element exists in the HashMap.
if (map.containsKey(temp)) {
// If it exists, it means there is a duplicate element in the array, so return true.
return true;
} else {
// If it doesn't exist, add the current element to the HashMap.
// The value '1' is used to indicate the existence of a duplicate element.
map.put(temp, 1);
}
}
// If there are no duplicate elements, return false.
return false;
}
}
Explanation
- HashSet internally uses HashMap. Therefore, you can achieve the same result using HashSet.
댓글 없음:
댓글 쓰기