Tags: LeetCode DSA Arrays & Hashing
Prompt:
Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
Example 1:
Input: nums = [1, 2, 3, 3]
Output: trueSolution
class Solution {
public:
bool hasDuplicate(vector<int>& nums)
{
std::unordered_map<int, bool> hashmap;
for(int num : nums)
{
if(!hashmap.contains(num))
{
hashmap[num] = false;
}
else
{
return true;
}
}
return false;
}
};Explanation
This one is pretty simple, you set up a hashmap and then you just check to see if the element exists in it, if it does not then you can add it, if it does already exist, return true, otherwise after you check them all, return false.
The reason why a hashmap is better than something like a vector of all integers in the size of nums is because we can hold integers that are greater than the size of nums, so like [100, 200, 500, 500]