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.

就是找出现频率前K个的数。想法就是用map统计出次数来。然后按次数排序。输出前K个数。

struct CmpByValue {  
  bool operator()(const pair& l, const pair& r) {  
    return l.second > r.second;  
  }  
};  

class Solution {
public:
    vector topKFrequent(vector& nums, int k) {
        map table;
        for(int i = 0; i < nums.size(); i++)
        {
            table[nums[i]]++ ;
        }
        vector >tableVec(table.begin(), table.end());
        sort(tableVec.begin(), tableVec.end(), CmpByValue());
        vector res;
        for(int i = 0; i

你可能感兴趣的:(347. Top K Frequent Elements 笔记)