#Leetcode# 347. Top K Frequent Elements

https://leetcode.com/problems/top-k-frequent-elements/

 

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

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.

代码:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> mp;
        priority_queue<pair<int, int> > q;
        vector<int> ans;
        
        for(int i = 0; i < nums.size(); i ++)
            mp[nums[i]] ++;
        
        for(auto i : mp)
            q.push({i.second, i.first});
        
        for(int i = 0; i < k; i ++) {
            ans.push_back(q.top().second);
            q.pop();
        }
        
        return ans;
    }
};

  FHFHFH 说了还有时间复杂度更低的做法明天更

八个月快落

posted @ 2019-01-29 22:25  丧心病狂工科女  阅读(140)  评论(0编辑  收藏  举报