# Leetcode 355 Solution

## Solution

``````struct Post
{
int id;
int time;
};

class User
{
public:
set<int> m_followees;
list<Post> m_posts;

void postTweet(int tweetId, int t)
{
Post post;
post.id = tweetId;
post.time = t;

m_posts.push_front(post);

if (m_posts.size() > 10)
m_posts.pop_back();
}

const list<Post>& getNewsFeed() {
return m_posts;
}

void follow(int followeeId) {
m_followees.insert(followeeId);
}

void unfollow(int followeeId) {
m_followees.erase(followeeId);
}
};

int t;

map<int, User> m_users;

User& findUser(int id)
{
if (m_users.find(id) == m_users.end())
m_users[id] = User();

return m_users[id];
}

public:
/** Initialize your data structure here. */
t = 0;
}

/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
auto& user = findUser(userId);
user.postTweet(tweetId, t++);
}

/** 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> ids;
ids.push_back(userId);

auto& curr_user = findUser(userId);
for (auto it = curr_user.m_followees.begin(); it != curr_user.m_followees.end(); it++)
ids.push_back(*it);

map<int, int> posts;

for (auto it = ids.begin(); it != ids.end(); it++)
{
auto& user = findUser(*it);
auto& l = user.getNewsFeed();
for (auto it2 = l.begin(); it2 != l.end(); it2++)
posts[it2->time] = it2->id;
}

vector<int> res;

for (auto it = posts.rbegin(); it != posts.rend(); it++)
{
res.push_back(it->second);

if (res.size() >= 10)
break;
}

return res;
}

/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
auto& user = findUser(followerId);
user.follow(followeeId);
}

/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
auto& user = findUser(followerId);
user.unfollow(followeeId);
}
};

/**
* obj.postTweet(userId,tweetId);
* vector<int> param_2 = obj.getNewsFeed(userId);
* obj.follow(followerId,followeeId);
* obj.unfollow(followerId,followeeId);
*/
``````