-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
most-frequent-ids.cpp
42 lines (40 loc) · 1.2 KB
/
most-frequent-ids.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
// Time: O(nlogn)
// Space: O(n)
// heap
class Solution {
public:
vector<long long> mostFrequentIDs(vector<int>& nums, vector<int>& freq) {
vector<long long> result;
unordered_map<int, int64_t> cnt;
priority_queue<pair<int64_t, int>> max_heap;
for (int i = 0; i < size(nums); ++i) {
cnt[nums[i]] += freq[i];
max_heap.emplace(cnt[nums[i]], nums[i]);
while (!empty(max_heap) && max_heap.top().first != cnt[max_heap.top().second]) {
max_heap.pop();
}
result.emplace_back(!empty(max_heap) ? max_heap.top().first : 0);
}
return result;
}
};
// Time: O(nlogn)
// Space: O(n)
// bst
class Solution2 {
public:
vector<long long> mostFrequentIDs(vector<int>& nums, vector<int>& freq) {
vector<long long> result;
unordered_map<int, int64_t> cnt;
map<int64_t, int> bst;
for (int i = 0; i < size(nums); ++i) {
if (--bst[cnt[nums[i]]] == 0) {
bst.erase(cnt[nums[i]]);
}
cnt[nums[i]] += freq[i];
++bst[cnt[nums[i]]];
result.emplace_back(rbegin(bst)->first);
}
return result;
}
};