File tree Expand file tree Collapse file tree 1 file changed +19
-2
lines changed Expand file tree Collapse file tree 1 file changed +19
-2
lines changed Original file line number Diff line number Diff line change 2
2
* @param {number[] } nums
3
3
* @return {boolean }
4
4
*/
5
+
6
+ //First method using Map() (exit early if true)
5
7
var containsDuplicate = function ( nums ) {
6
8
const numsSet = new Set ( )
7
9
for ( const i of nums ) {
@@ -10,5 +12,20 @@ var containsDuplicate = function(nums) {
10
12
}
11
13
numsSet . add ( i )
12
14
}
13
- return false
14
- } ;
15
+ return false ;
16
+ } ;
17
+
18
+ //Second method using Map() (Has to map entire array but code is more readable)
19
+ var containsDuplicate = function ( nums ) {
20
+ //create a new hashmap with all the items in the array. Any duplicates will be removed.
21
+ const totalWithoutDuplicates = new Map ( nums . map ( ( i ) => [ i ] ) ) ;
22
+
23
+ //check if the size of the initial array is larger than the new hashmap.
24
+ return totalWithoutDuplicates . size !== nums . length ;
25
+ } ;
26
+
27
+ //Third method using Set() (Fastest runtime at 91.95% and very readable code)
28
+ var containsDuplicate = function ( nums ) {
29
+ //Pass the array into a Set() (which removes duplicates) and then compare its size to the original array.
30
+ return new Set ( nums ) . size !== nums . length ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments