classTwitter{privatestaticint timeStamp =0;privateclassTweet{publicint id;publicint time;publicTweet nextTweet;publicTweet(int id){this.id = id;
time = timeStamp;++timeStamp;
nextTweet =null;}}privateclassUser{publicint id;publicSet<Integer> followed;publicTweet tweetHead;publicUser(int id){this.id = id;
followed =newHashSet<>();follow(id);// Follow itself
tweetHead =null;}publicvoidfollow(int id){
followed.add(id);}publicvoidunfollow(int id){
followed.remove(id);}publicvoidpost(int tweetId){Tweet t =newTweet(tweetId);// New post becomes the new head since it's the latest
t.nextTweet = tweetHead;
tweetHead = t;}}// userId -> User objectprivateMap<Integer,User> idToUser;publicTwitter(){
idToUser =newHashMap<>();}publicvoidpostTweet(int userId,int tweetId){if(!idToUser.containsKey(userId)){
idToUser.put(userId,newUser(userId));}
idToUser.get(userId).post(tweetId);}publicList<Integer>getNewsFeed(int userId){List<Integer> res =newLinkedList<>();// Check user presenceif(!idToUser.containsKey(userId))return res;// Obtain following accounts of the current userSet<Integer> followingIds = idToUser.get(userId).followed;// PQ to sort tweets according to their times// from latest to the oldestPriorityQueue<Tweet> pq =newPriorityQueue<Tweet>(
followingIds.size(),(a, b)->(b.time - a.time));// Add all the tweet heads from the followingIds to the pqfor(int id : followingIds){// Obtain its tweetHeadTweet t = idToUser.get(id).tweetHead;// Add to the pqif(t !=null){
pq.add(t);}}int count =0;// Obtain the latest 10 tweetswhile(!pq.isEmpty()&& count <10){// 加入最新的tweetTweet t = pq.poll();
res.add(t.id);++count;if(t.nextTweet !=null){// 然後再加入最新tweet的下一個,好繼續和其餘的做比較
pq.add(t.nextTweet);}}return res;}publicvoidfollow(int followerId,int followeeId){// Check follower and followee presenceif(!idToUser.containsKey(followerId)){
idToUser.put(followerId,newUser(followerId));}if(!idToUser.containsKey(followeeId)){
idToUser.put(followeeId,newUser(followeeId));}// Follow the followee
idToUser.get(followerId).follow(followeeId);}publicvoidunfollow(int followerId,int followeeId){// Check follower and followee presenceif(!idToUser.containsKey(followerId)||
followerId == followeeId){// Invalid operationreturn;}
idToUser.get(followerId).unfollow(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);
*/