Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:
- postTweet(userId, tweetId): Compose a new tweet.
- getNewsFeed(userId): 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.
- follow(followerId, followeeId): Follower follows a followee.
- unfollow(followerId, followeeId): Follower unfollows a followee.
class Twitter {
private Map<Integer, HashSet<Integer>> follow;
private Map<Integer, ArrayList<int[]>> tweet;
private int ts;
/** Initialize your data structure here. */
public Twitter() {
this.follow = new HashMap<Integer, HashSet<Integer>>();
this.tweet = new HashMap<Integer, ArrayList<int[]>>();
this.ts = 0;
}
/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
if(!tweet.containsKey(userId))
tweet.put(userId, new ArrayList<int[]>());
tweet.get(userId).add(new int[] {tweetId, ts++});
}
/** 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. */
public List<Integer> getNewsFeed(int userId) {
List<Integer> users = new ArrayList<Integer>();
users.add(userId);
if(follow.containsKey(userId)) {
HashSet<Integer> followee = follow.get(userId);
for(Integer f: followee) {
users.add(f);
}
}
List<int[]> tweets = new ArrayList<>();
for(Integer user: users) {
if(!tweet.containsKey(user))
continue;
List<int[]> t = tweet.get(user);
for(int i = t.size() - 1; i >= 0 && i >= t.size() - 10; i--) {
tweets.add(t.get(i));
}
}
Collections.sort(tweets, new Comparator<int[]>() {
public int compare(int[] i1, int[] i2) {
return i2[1] - i1[1];
}
});
List<Integer> res = new ArrayList<>();
for(int i = 0; i < 10 && i < tweets.size(); i++) {
res.add(tweets.get(i)[0]);
}
return res;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
public void follow(int followerId, int followeeId) {
if(followerId == followeeId)
return;
if(!this.follow.containsKey(followerId))
follow.put(followerId, new HashSet<Integer>());
follow.get(followerId).add(followeeId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
public void unfollow(int followerId, int followeeId) {
if(followerId == followeeId)
return;
if(!this.follow.containsKey(followerId))
return;
follow.get(followerId).remove(followeeId);
}
}
/**
* Your Twitter object will be instantiated and called as such:
* Twitter obj = new Twitter();
* obj.postTweet(userId,tweetId);
* List<Integer> param_2 = obj.getNewsFeed(userId);
* obj.follow(followerId,followeeId);
* obj.unfollow(followerId,followeeId);
*/