点击打开链接
//时间戳的使用
class Twitter {
public:
/** Initialize your data structure here. */
unordered_map<int, vector<pair<int, int>>> tweet;
unordered_map<int, unordered_set<int>> flwee;
int timestamp;
Twitter():timestamp(0) {
}
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
tweet[userId].push_back(make_pair(timestamp++, tweetId));// time small to big
}
/** 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>> nwsfd;
vector<int> ret;
int cnt = 0;
//self
while(cnt<10 && cnt<tweet[userId].size()){
nwsfd.push(tweet[userId][tweet[userId].size()-1-cnt]); //pair
cnt +=1;
}
//others
for(auto f:flwee[userId]){
cnt =0;
while(cnt<10 && cnt< tweet[f].size()){
nwsfd.push(tweet[f][tweet[f].size()-1-cnt]); //pair
cnt +=1;
}
}
for(int i=0; i<10; i++){
if(nwsfd.empty()) break;
ret.push_back(nwsfd.top().second);
nwsfd.pop();
}
return ret;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
if(followerId != followeeId){
flwee[followerId].insert(followeeId);
}
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
flwee[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);
*/
![](https://i-blog.csdnimg.cn/blog_migrate/e2a29afe2a50ccba5aa3b88c0ddc7bea.png)