Problem
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.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Solution
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:
- The
containsDuplicate
function takes an integer arraynums
as input and returns a boolean value indicating whether the array contains any duplicate elements. - It initializes a
Set
namedset
to store encountered elements. - The loop iterates through the array using a
for-each
loop. - Inside the loop:
- For each element
num
, theadd
method of theset
is called. If the element is already present in the set (i.e., it's a duplicate), theadd
method will returnfalse
, and the function immediately returnstrue
, indicating the presence of duplicates.
- For each element
- If the loop completes without finding any duplicates, the function returns
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/
Related Articles
- LeetCode 01 : Two Sum
- LeetCode 02 : Add Two Numbers
- LeetCode 03 : Longest Substring Without Repeating Characters
- LeetCode 04 : Container With Most Water
- LeetCode 05 : Remove Duplicates from Sorted Array
- LeetCode 06 : Maximum Subarray
- LeetCode 07 : Contains Duplicate
- Codechef 01 : Problem Code: AGELIMIT
- Codechef 02 : Problem Code: BURGERS