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 22 * @param {number[] } nums
33 * @return {boolean }
44 */
5+
6+ //First method using Map() (exit early if true)
57var containsDuplicate = function ( nums ) {
68 const numsSet = new Set ( )
79 for ( const i of nums ) {
@@ -10,5 +12,20 @@ var containsDuplicate = function(nums) {
1012 }
1113 numsSet . add ( i )
1214 }
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