diff --git a/javascript/217-Contains-Duplicate.js b/javascript/217-Contains-Duplicate.js index 6b4b91faf..e9912889e 100644 --- a/javascript/217-Contains-Duplicate.js +++ b/javascript/217-Contains-Duplicate.js @@ -2,6 +2,8 @@ * @param {number[]} nums * @return {boolean} */ + +//First method using Map() (exit early if true) var containsDuplicate = function(nums) { const numsSet = new Set() for(const i of nums){ @@ -10,5 +12,20 @@ var containsDuplicate = function(nums) { } numsSet.add(i) } - return false -}; \ No newline at end of file + return false; +}; + +//Second method using Map() (Has to map entire array but code is more readable) +var containsDuplicate = function(nums) { + //create a new hashmap with all the items in the array. Any duplicates will be removed. + const totalWithoutDuplicates = new Map(nums.map((i) => [i])); + + //check if the size of the initial array is larger than the new hashmap. + return totalWithoutDuplicates.size !== nums.length; +}; + +//Third method using Set() (Fastest runtime at 91.95% and very readable code) +var containsDuplicate = function(nums) { + //Pass the array into a Set() (which removes duplicates) and then compare its size to the original array. + return new Set(nums).size !== nums.length; +};
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: