This is a problem from GeeksForGeeks and I have tried to solve it on my own and I have written this code.
Given an array of size n, the goal is to find out the smallest number that is repeated exactly ‘k’ times where k > 0? Assume that array has only positive integers and 1 <= arr[i] < 1000 for each i = 0 to n -1.
Examples:
Input:
arr[] = {2 2 1 3 1} k = 2
Output: 1
Explanation:
Here in array:
- 2 is repeated 2 times
- 1 is repeated 2 times
- 3 is repeated 1 time
Hence 2 and 1 both are repeated 'k' times
i.e 2 and min(2, 1) is 1
Input:
arr[] = {3 5 3 2} k = 1
Output: 2
Explanation:
Both 2 and 5 are repeating 1 time but min(5, 2) is 2
How can I improve this code?
#include <iostream>
#include <vector>
#include <map>
template<class T>
void findElement(std::vector<T>& vec, int k)
{
std::map<T, int> count;
for(T x : vec)
{
count[x]++;
}
typename std::map<T, int>::iterator itr;
for(itr = count.begin(); itr != count.end(); itr++)
{
if(itr->second == k)
{
std::cout << itr->first <<'\n';
return;
}
}
std::cerr << "No such element \n ";
}
int main()
{
std::vector<char> v;
v.push_back('r');
v.push_back('t');
v.push_back('q');
v.push_back('r');
v.push_back('u');
v.push_back('q');
v.push_back('s');
int k;
std::cout << " Enter the number of repetitions you want : ";
std::cin >> k;
std::cout << "The smallest element that has " << k <<" reptition is : ";
findElement(v, k);
}
std::map
instead ofstd::unordered_map
because it sorts the element. \$\endgroup\$