1. Contains Duplicate
Problem 🔗
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.
Solution
Solution in C++ with hashmap
We can calculate the occurrences for each element of the array, using a hashmap. If a value appears more than once, true is returned, otherwise false is returned.
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> map;
for(int val : nums) {
if(map[val] > 0)
return true;
map[val]++;
}
return false;
}
- Time complexity:
(where n is the size of the vector) - Space complexity:
(we are storing all the input)