|
| 1 | +/* |
| 2 | + * @Author: xuezaigds@gmail.com |
| 3 | + * @Last Modified time: 2016-07-08 15:10:06 |
| 4 | + */ |
| 5 | + |
| 6 | +class Twitter { |
| 7 | + struct Tweet |
| 8 | + { |
| 9 | + int time; |
| 10 | + int id; |
| 11 | + Tweet(int time, int id) : time(time), id(id) {} |
| 12 | + }; |
| 13 | + |
| 14 | + struct compare{ |
| 15 | + bool operator()(const Tweet x, const Tweet y) { |
| 16 | + return x.time < y.time; |
| 17 | + } |
| 18 | + }; |
| 19 | + |
| 20 | + int time; |
| 21 | + unordered_map<int, vector<Tweet>> tweets; |
| 22 | + unordered_map<int, unordered_set<int>> followees; |
| 23 | + |
| 24 | +public: |
| 25 | + /** Initialize your data structure here. */ |
| 26 | + Twitter(): time(0) { |
| 27 | + } |
| 28 | + |
| 29 | + /** Compose a new tweet. */ |
| 30 | + void postTweet(int userId, int tweetId) { |
| 31 | + tweets[userId].push_back(Tweet(time++, tweetId)); |
| 32 | + } |
| 33 | + |
| 34 | + /** Retrieve the 10 most recent tweet ids in the user's news feed. |
| 35 | + Each item in the news feed must be posted by users who the user |
| 36 | + followed or by the user herself. |
| 37 | + Tweets must be ordered from most recent to least recent. */ |
| 38 | + vector<int> getNewsFeed(int userId) { |
| 39 | + priority_queue<Tweet, vector<Tweet>, compare> allnews; |
| 40 | + for(auto u: followees[userId]){ |
| 41 | + for(auto &t: tweets[u]){ |
| 42 | + allnews.push(t); |
| 43 | + } |
| 44 | + } |
| 45 | + for(auto &t: tweets[userId]){ |
| 46 | + allnews.push(t); |
| 47 | + } |
| 48 | + vector<int> ans; |
| 49 | + for(int i=0; i<10 && !allnews.empty(); i++){ |
| 50 | + ans.push_back(allnews.top().id); |
| 51 | + allnews.pop(); |
| 52 | + } |
| 53 | + return ans; |
| 54 | + } |
| 55 | + |
| 56 | + /** Follower follows a followee. If the operation is invalid, |
| 57 | + it should be a no-op. */ |
| 58 | + void follow(int followerId, int followeeId) { |
| 59 | + if(followerId != followeeId){ |
| 60 | + followees[followerId].insert(followeeId); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /** Follower unfollows a followee. If the operation is invalid, |
| 65 | + it should be a no-op. */ |
| 66 | + void unfollow(int followerId, int followeeId) { |
| 67 | + followees[followerId].erase(followeeId); |
| 68 | + } |
| 69 | +}; |
| 70 | + |
| 71 | +/** |
| 72 | + * Your Twitter object will be instantiated and called as such: |
| 73 | + * Twitter obj = new Twitter(); |
| 74 | + * obj.postTweet(userId,tweetId); |
| 75 | + * vector<int> param_2 = obj.getNewsFeed(userId); |
| 76 | + * obj.follow(followerId,followeeId); |
| 77 | + * obj.unfollow(followerId,followeeId); |
| 78 | + */ |
| 79 | + |
| 80 | +/* |
| 81 | +["Twitter","postTweet","postTweet","getNewsFeed","postTweet","getNewsFeed"] |
| 82 | +[[],[1,5],[1,3],[3,5],[1,6],[3,5,6]] |
| 83 | +["Twitter","postTweet","getNewsFeed","follow","postTweet","getNewsFeed","unfollow","getNewsFeed"] |
| 84 | +[[],[1,5],[1],[1,2],[2,6],[1],[1,2],[1]] |
| 85 | +*/ |
0 commit comments