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.
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <utility>
#include < unordered_map >
#include <queue>
using namespace std;
class CSolution{
public:
typedef pair<int, int> PAIR;
vector<int> topKFrequent(vector<int>& nums, int k){
unordered_map<int, int> count; // 哈希表,无序性,查找快,建立慢
for (int i = 0; i < nums.size(); i++){
count[nums[i]]++; //计数 count[元素,个数]
}
priority_queue<PAIR> q_pair; //优先队列,最大堆
for (auto it = count.begin(); it != count.end(); it++){
q_pair.push(PAIR(it->second, it->first));//res[个数,元素],按个数排序
}
vector<int> res;
for (int i = 0; i < k; i++){
res.push_back(q_pair.top().second); //res存储排序后的元素,按个数多到少排序
q_pair.pop();
}
return res;
}
};
map知识:
1.map类 - 模板类 - 头文件#include < unordered_map > 和 #include < map >
2.map的功能
自动建立Key - value的对应。key 和 value可以是任意你需要的类型。
根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。
快速插入Key - Value 记录。
快速删除记录
根据Key 修改value记录。
遍历所有记录。
3.map的基本操作函数:
C++ Maps是一种关联式容器,包含“关键字/值”对begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数
4.在map中插入元素
改变map中的条目非常简单,因为map类已经对[]操作符进行了重载
enumMap[1] = "One";
enumMap[2] = "Two";
.....
这样非常直观,但存在一个性能的问题。插入2时,先在enumMap中查找主键为2的项,没发现,然后将一个新的对象插入enumMap,键是2,值是一个空字符串,插入完成后,将字符串赋为"Two"; 该方法会将每个值都赋为缺省值,然后再赋为显示的值,如果元素是类对象,则开销比较大。我们可以用以下方法来避免开销:
enumMap.insert(map<int, CString> :: value_type(2, "Two"))
5、查找并获取map中的元素
下标操作符给出了获得一个值的最简单方法:
CString tmp = enumMap[2];
但是,只有当map中有这个键的实例时才对,否则会自动插入一个实例,值为初始化值。
我们可以使用Find()和Count()方法来发现一个键是否存在。