-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesign Twitter.cpp
More file actions
78 lines (70 loc) · 2.74 KB
/
Design Twitter.cpp
File metadata and controls
78 lines (70 loc) · 2.74 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
// Time complexity:
// postTweet: O(1);
// getNewsFeed: log(10 * log(n)), n is the average number of followers per user;
// follow: (unordered_set) average O(1), worst O(n)
// unfollow: average O(1)
class Twitter {
public:
/** Initialize your data structure here. */
struct Tweet {
int time;
int id;
Tweet(int time, int id) : time(time), id(id) {}
};
unordered_map<int, unordered_set<int>> followees; // userid -> vector of followees
unordered_map<int, vector<Tweet>> tweets; // userid -> vector of Tweet
int time_stemp;
Twitter() {
time_stemp = 0;
}
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
tweets[userId].emplace_back(time_stemp++, tweetId);
}
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
vector<int> getNewsFeed(int userId) {
map<int, vector<int>, greater<int>> mp; // [time] -> {tweetId, userId, pos in user’s tweets vector}
unordered_set<int> fl = followees[userId];
fl.insert(userId);
for (auto c : fl) {
if (tweets.find(c) != tweets.end()) {
vector<Tweet> toc = tweets[c];
int tailtime = toc.back().time;
int tailid = toc.back().id;
mp[tailtime] = {tailid, c, toc.size() - 1};
}
}
vector<int> tids;
for (int i=0; i<10; ++i) {
if (!mp.empty()) {
int key = mp.begin()->first;
vector<int> info = mp.begin()->second;
int tweetId = info[0]; int userid = info[1]; int pos = info[2];
tids.push_back(tweetId);
mp.erase(key);
if(pos > 0) {
mp[tweets[userid][pos-1].time] = {tweets[userid][pos-1].id, userid, pos-1};
}
} else {
break;
}
}
return tids;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
followees[followerId].insert(followeeId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
followees[followerId].erase(followeeId);
}
};
/**
* Your Twitter object will be instantiated and called as such:
* Twitter obj = new Twitter();
* obj.postTweet(userId,tweetId);
* vector<int> param_2 = obj.getNewsFeed(userId);
* obj.follow(followerId,followeeId);
* obj.unfollow(followerId,followeeId);
*/