• leetcode 347. Top K Frequent Elements


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

    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.

    解题思路

    O(N + N*longN) 的解法

    先用无序哈希表记录数字出现次数,然后插入到最大堆中,最后从堆中取出前 K 个元素并返回。

    struct FrequencyCmp {
    	bool operator() (const pair<int, unsigned int> &lhs, pair<int, unsigned int> &rhs) {
    		return  lhs.second < rhs.second ? true : false;
    	}
    };
    
    class Solution {
    public:
    	vector<int> topKFrequent(vector<int>& nums, int k) {
    		unordered_map<int, unsigned int> numberFrequency;
    
    		for (auto e : nums) {
    			numberFrequency[e]++;
    		}
    
    		priority_queue<pair<int, unsigned int>, vector<pair<int, unsigned int>>, FrequencyCmp> heap;
    
    		for (auto e : numberFrequency) {
    			heap.push(e);
    		}
    
    		vector<int> v;
    
    		for (int i = 0; i < k; i++) {
    			v.push_back(heap.top().first);
    			heap.pop();
    		}
    
    		return v;
    	}
    };
    
  • 相关阅读:
    Data Wrangling文摘:Non-tidy-data
    Data Wrangling文摘:Tideness
    Python文摘:Mixin 2
    Python文摘:Mixin
    Python文摘:Python with Context Managers
    Python学习笔记11
    SQL学习笔记9
    SQL学习笔记8
    SQL学习笔记7
    Python学习笔记10:内建结构
  • 原文地址:https://www.cnblogs.com/fengyubo/p/5848951.html
Copyright © 2020-2023  润新知