LeetCode 347. Top K Frequent Elements

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].

hashmap + heap

#include <vector>
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;

// Using a hashmap
typedef pair<int, int> data;
vector<int> topKFrequent(vector<int>& nums, int k) {
  vector<int> res;
  unordered_map<int, int> numToCount;
  for(int i = 0; i < nums.size(); ++i) {
    if(numToCount.find(nums[i]) == numToCount.end()) {
      numToCount.insert({nums[i], 1});
    } else {
      ++numToCount[nums[i]];
    }
  }
  priority_queue<data, vector<data>, greater<data> > minHeap;
  auto iter = numToCount.begin();
  while(iter != numToCount.end()) {
    minHeap.push(make_pair(iter->second, iter->first));
    if(minHeap.size() > k) {minHeap.pop();}
    iter++;
  }
  while(!minHeap.empty()) {
    res.push_back(minHeap.top().second);
    minHeap.pop();
  }
  return res;
}

int main(void) {
  vector<int> nums{1, 1, 1, 2, 2, 3};
  vector<int> res = topKFrequent(nums, 2);
  for(int i = 0; i < res.size(); ++i) cout << res[i] << endl;
}


你可能感兴趣的:(LeetCode 347. Top K Frequent Elements)