[Leetcode] Blind75 Contain duplicate
Question 217
hash table
Question
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.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Explanation:
The element 1 occurs at the indices 0 and 3.
Example 2:
Input: nums = [1,2,3,4]
Output: false
Explanation:
All elements are distinct.
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
1 <= nums.length <= 105109 <= nums[i] <= 109
My Solution
/**
* @param {number[]} nums
* @return {boolean}
*/
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], 1)
}
return false
};
Key Takeaway
I used a hash map to efficiently check if the array contains duplicates. By leveraging the hash map's constant time complexity for insertion and lookup O(1), I was able to iterate through the array in linear time O(n).
Here’s how it works:
- As I iterate through the array, I check if the current value already exists in the hash map.
- If it does, the function immediately returns
true, indicating a duplicate is found. - If not, I add the current value as a key in the hash map and continue.
This approach is both time-efficient and simple to implement. While the space complexity is O(n) due to the hash map, it's a reasonable trade-off for the performance gain, especially compared to less efficient O(n^2) brute-force methods.
Comments ()