1. 程式人生 > >#Leetcode# 347. Top K Frequent Elements

#Leetcode# 347. Top K Frequent Elements

urn com tar map 代碼 href first 說了 ret

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 說了還有時間復雜度更低的做法明天更

八個月快落

#Leetcode# 347. Top K Frequent Elements