Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user’s news feed. Your design should support the following methods:
postTweet(userId, tweetId): Compose a new tweet.
getNewsFeed(userId): 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.
follow(followerId, followeeId): Follower follows a followee.
unfollow(followerId, followeeId): Follower unfollows a followee.
Info getNthFeedInfo(int userId, int n){ pair<int, int> feed = getNthFeed(userId, n); return {userId, feed.first, feed.second}; } public: /** Initialize your data structure here. */ Twitter() { time = 0; }
/** Compose a new tweet. */ voidpostTweet(int userId, int tweetId){ feeds[userId].push_front({time++, 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){ vector<int> res; map<int, int> followings; priority_queue<Info> pq;
while(!pq.empty() && res.size() < 10 && pq.top().time != INT_MIN) { Info info = pq.top(); pq.pop(); res.push_back(info.tweetId); pq.push(getNthFeedInfo(info.followee, ++followings[info.followee])); }
return res; }
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */ voidfollow(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. */ voidunfollow(int followerId, int followeeId){ if(followerId ^ followeeId) follows[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); */