zoukankan      html  css  js  c++  java
  • 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;
    	}
    };
    
  • 相关阅读:
    170325 第六章应用层 域名系统 DNS
    文件操作(Linux系统调用)
    进程优先级,进程nice值和%nice的解释
    常用的操作系统进程调度算法
    fork函数返回值问题
    进度条的实现
    find命令
    单链表的插入排序
    B树
    排序
  • 原文地址:https://www.cnblogs.com/fengyubo/p/5848951.html
Copyright © 2011-2022 走看看