c++
class weibo {
public:
weibo() {}
weibo(int a, int b, int c) : usr(a), twt(b), time(c) {}
int usr;//usr_id
int twt;//twitter content
int time;//time
inline bool operator<(const weibo &x) const { return time > x.time; }
};
class Twitter {
private:
unordered_map<int, set<weibo>> cache_self;
unordered_map<int, unordered_set<int>> usr_follow;
long long cur_time = 0;//current time
int Max_Num=10;
public:
/** Initialize your data structure here. */
Twitter() { }
/** Compose a new tweet. */
void postTweet(int userId, int 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);
// User 1 follows user 2.
// twitter.follow(1, 2);
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId);
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId);
};
void Twitter::postTweet(int userId, int tweetId) {
weibo a_weibo(userId, tweetId, cur_time++);
cache_self[userId].insert(a_weibo);
usr_follow[userId].insert(userId);
}
vector<int> Twitter::getNewsFeed(int userId) {
if (usr_follow.find(userId) == usr_follow.end())//not exist
return vector<int>();
set<weibo> res;
for (auto &usr : usr_follow[userId]) {
for (auto &wei : cache_self[usr]) {
res.insert(wei);
}
}
int num = min(Max_Num, int(res.size()));
vector<int> ret;
int cnt = 0;
for (auto &v : res) {
if (cnt++ >= 10)
break;
ret.push_back(v.twt);
}
return ret;
}
void Twitter::follow(int followerId, int followeeId) {
usr_follow[followerId].insert(followeeId);
}
void Twitter::unfollow(int followerId, int followeeId) {
if (followerId == followeeId)
return;
usr_follow[followerId].erase(followeeId);
}
python
#https://leetcode.com/discuss/107656/python-solution
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.timer = itertools.count(step=-1)
self.tweets = collections.defaultdict(collections.deque)
self.followees = collections.defaultdict(set)
def postTweet(self, userId, tweetId):
a_weibo = (next(self.timer), tweetId)
self.tweets[userId].appendleft(a_weibo)
def getNewsFeed(self, userId):
follow_id = (self.tweets[u] for u in (self.followees[userId] | {userId}))
tweets = heapq.merge(*follow_id)
return [t for _, t in itertools.islice(tweets, 10)]
def follow(self, followerId, followeeId):
self.followees[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
self.followees[followerId].discard(followeeId)
reference:
heapq: https://docs.python.org/2/library/heapq.html
collection: http://www.tuicool.com/articles/YbmYbyf