Created
December 19, 2021 00:49
-
-
Save IEdiong/a003cffc27ebea524b30619bf71916b2 to your computer and use it in GitHub Desktop.
LeetCode Data Structure I: Day 1 - 001
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 217. Contains Duplicate | |
// Easy | |
// Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. | |
const containsDuplicate = (nums) => { | |
// create an empty dictionary | |
// iterate through the array | |
// for each integer in the array check if the integer position exists in the dictionary | |
// if 'yes' return 'true' | |
// else add the integer's position to the dict and intialize it with a value of 1 | |
// after the loop return false | |
const dict = []; | |
for (let num of nums) { | |
if (dict[num]) return true; | |
dict[num] = 1; | |
} | |
return false; | |
}; | |
// Time: O(n) | |
// Space: O(1) | |
console.log(containsDuplicate([1, 2, 3, 1])); | |
console.log(containsDuplicate([1, 2, 3, 4])); | |
console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment