[Leetcode] 347. Top K Frequent Elements 解题报告

来源:互联网 发布:mac版spss使用教程 编辑:程序博客网 时间:2024/06/09 13:54

题目

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

Note: 

  • You may assume k is always valid, 1 ? k ? number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

思路

分为三个步骤:

1)构建一个哈希表,其中key是数组元素,value是它在nums中的出现次数。

2)构建一个优先队列,将哈希表中的元素加入优先队列中;但是此时我们将key设为数组元素的出现次数,value则成为对应的数组元素,因为这样出现次数最多的元素每次都会被调整到优先队列的顶端。

3)依次从优先队列中取出k个元素,并返回该k个元素构成的数组。

算法的时间复杂度是O(klogn),空间复杂度是O(n)(不过我感觉这里的空间复杂度严格来讲是输入敏感型的,也就是说如果n个元素中有m个不同的元素,则空间复杂度是O(m),其中k <= m <= n)。

代码

class Solution {public:    vector<int> topKFrequent(vector<int>& nums, int k) {        unordered_map<int, int> hash;        for (int i = 0; i < nums.size(); ++i) {            ++hash[nums[i]];        }        priority_queue<pair<int, int>> pq;        for (auto it = hash.begin(); it != hash.end(); ++it) {            pq.push(make_pair(it->second, it->first));        }        vector<int> ret;        for (int i = 0; i < k; ++i) {            ret.push_back(pq.top().second);            pq.pop();        }        return ret;    }};

原创粉丝点击