The pattern
Any time a question contains the words count, frequency, duplicate, anagram, most common or seen before, the answer starts with a hash map. A nested loop that recounts the array for every element is O(n^2); one pass building a count map is O(n).
The trade is memory: you spend O(k) space, where k is the number of distinct values, to save a factor of n in time. Almost always worth it.
The three tools
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
using namespace std;
int main() {
vector<int> a = {4, 2, 4, 7, 2, 4};