Today I am going to show how to solve the Leetcode Contains Duplicate algorithm problem.
Solution:
I use a hash table for solving this problem. In the hash table Iām going to map each element (as a key) to its index (as a value).
1) For creating a hash table, Iām using a new data structure called Map, which was introduced in ECMAScript 2015.
var containsDuplicate = function(nums) {
let map = new Map();
};
2) Next, I iterate through all of the numbers using for loop.
var containsDuplicate = function(nums) {
let map = new Map();
for (let i = 0; i < nums.length; i++) {
}
};
3) While I iterate the elements, I also check if the current element already exists in the table. If it exists, the function will break out of the loop and return true. Otherwise, I insert an element into the table.
var containsDuplicate = function(nums) {
let map = new Map();
for (let i = 0; i < nums.length; i++) {
if (map.has(nums[i])) {
return true
}
map.set(nums[i], i)
}
return false
};
Top comments (1)
I have way simpler solution: