File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments