题目描述
blablabla
样例
blablabla
just edited yxc original with priority_queue
C++ 代码
class Twitter {
public:
/** Initialize your data structure here. */
unordered_map<int, vector<pair<int, int>>> posts;
unordered_map<int, unordered_set<int>> follows;
int id = 0;
Twitter() {
}
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
posts[userId].push_back(make_pair(id++, 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) {
priority_queue<pair<int,int>, vector<pair<int,int>>, less<pair<int,int>>> pq;
for (auto x : posts[userId]) pq.push(x);
for (auto follow : follows[userId])
for (auto x : posts[follow])
pq.push(x);
vector<int> res;
int n = pq.size();
for (int i = 0; i < 10 && i < n; i++) {
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
if (followerId != followeeId)
follows[followerId].insert(followeeId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
follows[followerId].erase(followeeId);
}
};
blablabla