forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
74 lines (56 loc) · 1.62 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/// Source : https://leetcode.com/problems/top-k-frequent-elements/description/
/// Author : liuyubobobo
/// Time : 2017-11-17
#include <iostream>
#include <vector>
#include <unordered_map>
#include <set>
#include <cassert>
using namespace std;
/// Using Tree Set
/// Time Complexity: O(nlogn)
/// Space Complexity: O(n)
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
assert(k > 0);
unordered_map<int, int> freq;
for(int num: nums)
freq[num] ++;
// cout << "freq:" << endl;
// for(pair<int, int>p: freq)
// cout << "v: " << p.first << " f: " << p.second << endl;
// cout << endl;
assert(k <= freq.size());
set<pair<int, int>, greater<pair<int, int>>> record;
for(pair<int, int> p: freq)
record.insert(make_pair(p.second, p.first));
vector<int> res;
for(int i = 0 ; i < k ; i ++){
set<pair<int, int>>::iterator iter = record.begin();
advance(iter, i);
assert(iter != record.end());
res.push_back(iter->second);
}
return res;
}
};
void printVec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
int nums1[] = {1, 1, 1, 2, 2, 3};
vector<int> vec1(nums1, nums1 + sizeof(nums1)/sizeof(int));
int k1 = 2;
printVec(Solution().topKFrequent(vec1, k1));
// 1, 2
// ---
int nums2[] = {1, 2};
vector<int> vec2(nums2, nums2 + sizeof(nums2)/sizeof(int));
int k2 = 2;
printVec(Solution().topKFrequent(vec2, k2));
// 1, 2
return 0;
}