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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| struct tweet { tweet(int i = 0, int t = 0) { id = i; time = t; } int id; int time; };
struct user { list<tweet> tweets; list<int> following; };
class Twitter { public: Twitter() { user_table.clear(); cur_time = 1; } void postTweet(int userId, int tweetId) { user_table[userId].tweets.push_front(tweet(tweetId, cur_time++)); if (user_table[userId].tweets.size() > 10) user_table[userId].tweets.pop_back(); } vector<int> getNewsFeed(int userId) { vector<tweet> temp_ans(user_table[userId].tweets.begin(), user_table[userId].tweets.end());
for (list<int>::iterator iter = user_table[userId].following.begin(); iter != user_table[userId].following.end(); ++iter) { if (*iter == userId) continue;
vector<tweet> temp(temp_ans); temp_ans.clear(); vector<tweet>::iterator temp_it = temp.begin(); for (list<tweet>::iterator jter = user_table[*iter].tweets.begin(); jter != user_table[*iter].tweets.end(); ++jter) { if (temp_it != temp.end()) { if (temp_it->time < jter->time) { temp_ans.push_back(*jter); } else { temp_ans.push_back(*temp_it); ++temp_it; --jter; } } else { temp_ans.push_back(*jter); } if (temp_ans.size() == 10) break; } while (temp_it != temp.end()) { if (temp_ans.size() == 10) break; temp_ans.push_back(*temp_it); ++temp_it; } }
vector<int> ans; for (vector<tweet>::iterator it = temp_ans.begin(); it != temp_ans.end(); ++it) ans.push_back(it->id);
return ans; } void follow(int followerId, int followeeId) { for (list<int>::iterator it = user_table[followerId].following.begin(); it != user_table[followerId].following.end(); ++it) if (*it == followeeId) return; user_table[followerId].following.push_back(followeeId); } void unfollow(int followerId, int followeeId) { for (list<int>::iterator it = user_table[followerId].following.begin(); it != user_table[followerId].following.end(); ++it) if (*it == followeeId) { user_table[followerId].following.erase(it); break; } }
private: unordered_map<int, user> user_table; int cur_time; };
|