Leetcode [217] - Contains Duplicates (Java Solution)
Leetcode [217] - Contains Duplicates (Java Solution)
Category: Easy
What is used: HashSet
Question
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Explanation: 1 is repeated twice.
Example 2:
Input: [1,2,3,4]
Output: false
Explanation: No number in the array is repeated.
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
Note:
- 1 <= A.length <= 100
- 1 <= A[i].length <= 100
Solution
I am using HashSet to solve this problem. There are various different methods to solve this problem but this is one the most straight forward and simple way. Learn more about HashSets here at: https://www.geeksforgeeks.org/hashset-in-java/
I traverse through the array and add elements one by one to the HashSet and as soon as the duplicate is encountered, return true. Else when entire array is traversed, return false.
class Solution {
public boolean containsDuplicate(int[] nums) {
int i = 0;
HashSet<Integer> hs = new HashSet();
while (i < nums.length){
if(!hs.contains(nums[i])){
hs.add(nums[i]);
i++;
} else {
return true;
}
}
return false;
}
}
Time complexity:
The time complexity of this code is O(n)
Submission Details:
Runtime: 8 ms
Memory Usage: 44.1 MB
Clap to support the author, help others find it, and make your opinion count.