Skip to content

Commit 8ae6dff

Browse files
committed
Solutions for Contains Duplicate #217
1 parent 0e5ffe5 commit 8ae6dff

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

contains-duplicate/dohyeon2.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.util.HashSet;
2+
3+
class Solution {
4+
// The problem is to check if there are any duplicate elements in the array.
5+
// So, I decided to use HashSet because it has O(1) time complexity for add and contains operations which are good to use for checking duplicates.
6+
public boolean containsDuplicate(int[] nums) {
7+
// the element type of the array is int, so create Integer HashSet
8+
// O(n) space complexity
9+
HashSet<Integer> exists = new HashSet<Integer>();
10+
// the nums array has length up to 10^5, so use int type
11+
// O(n) time complexity average
12+
// worst case: O(n log n) if many elements hash to the same bucket
13+
for(int i = 0; i < nums.length; i++){
14+
int num = nums[i];
15+
16+
if(exists.contains(num)){
17+
return true;
18+
}else{
19+
exists.add(num);
20+
}
21+
}
22+
return false;
23+
}
24+
}

0 commit comments

Comments
 (0)