-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
103 lines (92 loc) · 2.39 KB
/
main.cpp
File metadata and controls
103 lines (92 loc) · 2.39 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Source: https://leetcode.com/problems/top-k-frequent-elements
// Title: Top K Frequent Elements
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given an integer array `nums` and an integer `k`, return the `k` most frequent elements. You may return the answer in **any order**.
//
// **Example 1:**
//
// ```
// Input: nums = [1,1,1,2,2,3], k = 2
// Output: [1,2]
// ```
//
// **Example 2:**
//
// ```
// Input: nums = [1], k = 1
// Output: [1]
// ```
//
// **Example 3:**
//
// ```
// Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
// Output: [1,2]
// ```
//
// **Constraints:**
//
// - `1 <= nums.length <= 10^5`
// - `-10^4 <= nums[i] <= 10^4`
// - `k` is in the range `[1, the number of unique elements in the array]`.
// - It is **guaranteed** that the answer is **unique**.
//
// **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <functional>
#include <queue>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
// Sort, (n log n)
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
// Frequency
auto freqMap = unordered_map<int, int>();
for (auto num : nums) {
++freqMap[num];
}
// Sort frequency
auto freqs = vector<pair<int, int>>();
for (auto [num, freq] : freqMap) freqs.push_back({freq, num});
sort(freqs.begin(), freqs.end(), greater());
// Answer
auto ans = vector<int>();
for (auto i = 0; i < k; ++i) {
ans.push_back(freqs[i].second);
}
return ans;
}
};
// Heap, (n log k)
class Solution2 {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
// Frequency
auto freqMap = unordered_map<int, int>();
for (auto num : nums) {
++freqMap[num];
}
// Heap
auto heap = priority_queue<pair<int, int>>();
for (auto [num, freq] : freqMap) {
heap.push({-freq, num});
if (heap.size() > k) {
heap.pop();
}
}
// Answer
auto ans = vector<int>();
while (!heap.empty()) {
ans.push_back(heap.top().second);
heap.pop();
}
return ans;
}
};