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.
Input: nums = [1,2,3,1]
Output: true
Input: nums = [1,2,3,4]
Output: false
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int num : nums){
if(!set.add(num)){
return true;
}
}
return false;
}
}
The above solution is for the "Contains Duplicate" problem. It checks whether there are any duplicate elements in the given integer array nums
. Here's how the code works:
containsDuplicate
function takes an integer array nums
as input and returns a boolean value indicating whether the array contains any duplicate elements.Set
named set
to store encountered elements.for-each
loop.num
, the add
method of the set
is called. If the element is already present in the set (i.e., it's a duplicate), the add
method will return false
, and the function immediately returns true
, indicating the presence of duplicates.false
.The code efficiently uses a Set
data structure to keep track of encountered elements. If an element is already present in the set, it means a duplicate has been found. Otherwise, the element is added to the set for future comparison.
This code provides a simple and efficient solution to determine whether an array contains duplicate elements.
Original Problem: https://leetcode.com/problems/contains-duplicate/