Skip to content

Commit 7785c45

Browse files
committed
top-k-frequent sol
1 parent 88165ec commit 7785c45

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed
Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
11
class Solution {
22
public:
3-
int longestConsecutive(vector<int>& nums) {
4-
const int INF = 987654321;
5-
int temp = INF, ret = 0, cur = 0;
3+
vector<int> topKFrequent(vector<int>& nums, int k) {
4+
map<int, int> mp;
5+
priority_queue<pair<int, int>> pq;
6+
vector<int> ans;
67

7-
sort(nums.begin(), nums.end());
8-
for(int a : nums){
9-
if(a == temp)continue;
10-
if(temp == INF || temp + 1 == a){
11-
cur++; temp = a;
12-
} else {
13-
ret = max(ret, cur);
14-
cur = 1;
15-
temp = a;
16-
}
17-
}
18-
ret = max(ret, cur);
19-
return ret;
8+
for(auto b : nums) mp[b]++;
9+
10+
for(auto p : mp) pq.push({p.second, p.first});
11+
12+
while(k--)ans.push_back(pq.top().second), pq.pop();
13+
14+
return ans;
2015
}
2116
};

0 commit comments

Comments
 (0)