Given a non-empty array of integers, return the k most frequent elements.
For example, given [1,1,1,2,2,3]
and k = 2
, return [1,2]
.
Following is my submission to this problem on Leetcode and it is accepted. Can you please provide feedback on any issue that you see in this code? I am looking for improvements in the quality of the code from both software engineering perspective as well as from algorithmic complexity or space and run-time performance perspective.
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
class Node
{
public:
int value{};
unsigned frequency{};
Node()
{
}
Node (int value, unsigned frequency)
{
this->value = value;
this->frequency = frequency;
}
bool operator< (const Node& other)
{
return this->frequency < other.frequency;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k)
{
map<int, unsigned> frequency;
for (auto n : nums )
{
if ( frequency.find(n) != frequency.end())
frequency[n]++;
else
frequency[n] = 0;
}
vector<Node> heap;
for ( auto f : frequency )
heap.push_back(Node(f.first, f.second));
make_heap(heap.begin(), heap.end());
vector<int> result;
unsigned i = 0;
while ( i < k )
{
result.push_back(heap.front().value);
pop_heap(heap.begin(), heap.end()-i);
i++;
}
return result;
}
};