Leetcode 217. Contains Duplicate
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.
1 <= nums.length <= 10^5
.-10^9 <= nums[i] <= 10^9
.To solve this problem, we can use a HashSet
to track the elements we have encountered so far. The idea is simple:
HashSet
.
true
as we have found a duplicate.HashSet
.false
.This approach ensures that we only traverse the array once and each lookup/addition operation in a HashSet
is O(1) on average.
Here is the Java implementation of the solution:
import java.util.HashSet;
public class ContainsDuplicate {
public static boolean containsDuplicate(int[] nums) {
// Create a HashSet to store unique elements
HashSet<Integer> set = new HashSet<>();
// Traverse the array
for (int num : nums) {
// Check if the element is already in the set
if (set.contains(num)) {
return true; // Duplicate found
}
// Add the element to the set
set.add(num);
}
// No duplicates found
return false;
}
public static void main(String[] args) {
int[] nums1 = {1, 2, 3, 4};
System.out.println(containsDuplicate(nums1)); // Output: false
int[] nums2 = {1, 2, 3, 1};
System.out.println(containsDuplicate(nums2)); // Output: true
}
}
HashSet
is O(1) on average.HashSet
, which would require O(n) space.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?