1. Contains Duplicate

#leetcode/217

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;
}