您的位置:首页 > 产品设计 > UI/UE

Top K Frequent Elements

2016-06-23 12:41 363 查看
做题涉及到的知识:

1、堆排序中建堆过程时间复杂度O(n):

这是一个bottom-up的建堆。于是,有1/2的元素向下比较了一次,有1/4的向下比较了两次,1/8的,向下比较了3次,......,1/2^k的向下比较了k次,其中1/2^k <= 1, k 约等于lg(n)。于是就有总的比较量:

T = () * n

令 S =

1/2 S =

S - 1/2S = 1/2S =

到这步就很明显了吧,S <= 2

于是T <= 2n => T = O(n).

2、用STL提供的sort算法对map排序:

struct CmpByValue {
bool operator()(const pair<string,int> & lhs, const pair<string,int> & rhs)
{return lhs.second > rhs.second;}
};
...
map<string,int> substr;
vector<pair<string,int>> counts(substr.begin(),substr.end());
sort(counts.begin(),counts.end(),CmpByValue());
3、通过map统计后用最大优先队列(最大堆)排序

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
//一,统计处频次
unordered_map<int,int> mapping;
for(int number : nums)
mapping[number]++;
//二,根据频次压入最大堆中
// pair<first, second>: first is frequency,  second is number
priority_queue<pair<int,int>> pri_que; //最大堆
for(auto it = mapping.begin(); it != mapping.end(); it++)
pri_que.push(make_pair(it->second, it->first));
//三,获取结果
while(result.size() < k){
result.push_back(pri_que.top().second);
pri_que.pop();
}
return result;
}
private:
vector<int> result;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: