https://leetcode.com/problems/design-twitter/
class Twitter {
unordered_map<int, set<int> > follower_mp;
unordered_map<int, set<int> > followee_mp;
unordered_map<int, vector<pair<int, int> > > twitter_self_mp;
int timestamp;
public:
/** Initialize your data structure here. */
Twitter() {
timestamp = ;
}
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
if (twitter_self_mp.find(userId) == twitter_self_mp.end()) {
vector<pair<int, int> > tmp_vec;
twitter_self_mp[userId] = tmp_vec;
}
timestamp++;
twitter_self_mp[userId].insert(twitter_self_mp[userId].begin(), make_pair(timestamp, 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) {
set<int> tmp_set;
if (follower_mp.find(userId) != follower_mp.end()) {
tmp_set = follower_mp[userId];
}
tmp_set.insert(userId);
vector<pair<int, int> > result;
set<int>::iterator itr = tmp_set.begin();
for (; itr != tmp_set.end(); ++itr) {
if (twitter_self_mp.find(*itr) == twitter_self_mp.end()) {
continue;
}
int curPos = ;
int curSize = result.size();
vector<pair<int, int> > tmp_vec = twitter_self_mp[*itr];
vector<pair<int, int> >::iterator vitr = tmp_vec.begin();
for (; vitr != tmp_vec.end() && curPos < ; ++vitr) {
while (curPos < && curPos < curSize &&
result[curPos].first > vitr->first) {
curPos++;
}
if (curPos >= ) {
break;
}
result.insert(result.begin() + curPos,
*vitr);
curPos++;
curSize++;
}
}
vector<int> ret;
int rlen = result.size();
for (int i=; i< && i<rlen; ++i) {
ret.push_back(result[i].second);
}
return ret;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
if (follower_mp.find(followerId) == follower_mp.end()) {
set<int> tmp_set;
follower_mp[followerId] = tmp_set;
}
follower_mp[followerId].insert(followeeId);
if (followee_mp.find(followeeId) == followee_mp.end()) {
set<int> tmp_set;
followee_mp[followeeId] = tmp_set;
}
followee_mp[followeeId].insert(followerId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
if (follower_mp.find(followerId) != follower_mp.end() &&
follower_mp[followerId].find(followeeId) != follower_mp[followerId].end()) {
follower_mp[followerId].erase(followeeId);
}
if (followee_mp.find(followeeId) != followee_mp.end() &&
followee_mp[followeeId].find(followerId) != followee_mp[followeeId].end()) {
followee_mp[followeeId].erase(followerId);
}
}
};
/**
* 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);
*/