給定一個非空的整數數組,返回其中出現頻率前 k 高的元素。
- 示例 1:
輸入: nums = [1,1,1,2,2,3], k = 2
輸出: [1,2]
示例 2:輸入: nums = [1], k = 1
輸出: [1]
提示:
你可以假設給定的 k 總是合理的,且 1 ≤ k ≤ 數組中不相同的元素的個數。
你的算法的時間復雜度必須優于 O(n log n) , n 是數組的大小。
題目數據保證答案唯一,換句話說,數組中前 k 個高頻元素的集合是唯一的。
你可以按任意順序返回答案。
// 時間復雜度:O(nlogk)
// 空間復雜度:O(n)
class Solution {
public:// 小頂堆class myCompare {public:bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {return lhs.second > rhs.second;}};vector<int> topKFrequent(vector<int>& nums, int k) {map<int, int> m;for (const auto& x: nums) {m[x]++;}priority_queue<pair<int, int>, vector<pair<int, int>>, myCompare> my_pri;auto iter = m.begin();for (int i=0; i<k; i++) {my_pri.push(*iter);iter++;}for (; iter != m.end(); iter++) {my_pri.push(*iter);my_pri.pop();}vector<int> res;while(my_pri.size() > 0) {res.push_back(my_pri.top().first);my_pri.pop();}return res;}
};