Design Twitter LeetCode solution in C++

1
class Twitter {
2
public:
3
map<int, priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>> user;
4
map<int, set<int>> connect;
5
int time = 0;
6
Twitter() {}
7

8
void postTweet(int userId, int tweetId) {
9
user[userId].push({time, tweetId}); // stores as (time,tweet) pair to min heap
10
time++;
11
if (user[userId].size() > 10) // keeping max 10 recents post of a user
12
user[userId].pop();
13
}
14
void fun(priority_queue<pair<int, int>> &pq,
15
int id) // add elements from min heap(id) to max heap(pq)
16
{
17
vector<vector<int>> temp;
18
while (!user[id].empty()) {
19
int a = user[id].top().first;
20
int b = user[id].top().second;
21
user[id].pop();
22
pq.push({a, b});
23
temp.push_back({a, b});
24
}
25
for (auto x : temp) {
26
user[id].push({x[0], x[1]});
27
}
28
}
29
vector<int> getNewsFeed(int userId) {
30
vector<int> v;
31
priority_queue<pair<int, int>> pq;
32
fun(pq, userId); // user itself
33
for (auto x : connect[userId]) // posts by followers
34
{
35
fun(pq, x);
36
}
37
int i = 0;
38
while (!pq.empty()) {
39
v.push_back(pq.top().second);
40
pq.pop();
41
i++;
42
if (i == 10) break;
43
}
44
return v;
45
}
46

47
void follow(int followerId, int followeeId) {
48
connect[followerId].insert(followeeId);
49
}
50

51
void unfollow(int followerId, int followeeId) {
52
connect[followerId].erase(followeeId);
53
}
54
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0