Skip to content

Commit ca7dbc4

Browse files
Merge pull request #224 from qasimala/main
Added two additional methods - 217 Contains Duplicates
2 parents 8ecb50d + 45a6b65 commit ca7dbc4

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

javascript/217-Contains-Duplicate.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
* @param {number[]} nums
33
* @return {boolean}
44
*/
5+
6+
//First method using Map() (exit early if true)
57
var 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+
};

0 commit comments

Comments
 (0)