/** 355. Design Twitter * 2016-7-13 by Mingyang * System designs are really broken.*/ classTwitter {Private Static intTimestamp=0; //Easy to find if user exist PrivateMap<integer, user>UserMap; //Tweet link to next tweet so, we can save a lot of time//When we execute Getnewsfeed (userId) Private classtweet{ Public intID; Public intTime ; PublicTweet Next; PublicTweets (intID) { This. ID =ID; time= timestamp++; Next=NULL; } } //OO Design So User can follow, unfollow and post itself Public classuser{ Public intID; PublicSet<integer>followed; PublicTweet Tweet_head; PublicUser (intID) { This. id=ID; Followed=NewHashset<>(); Follow (ID); //First follow itselfTweet_head =NULL; } Public voidFollow (intID) {Followed.add (ID); } Public voidUnfollow (intID) {followed.remove (ID); } //everytime user post a new tweet, add it to the head of the tweet list. Public voidPostintID) {Tweet T=NewTweet (ID); T.next=Tweet_head; Tweet_head=T; } } /**Initialize your data structure here.*/ PublicTwitter () {UserMap=NewHashmap<integer, user>(); } /**Compose a new tweet.*/ Public voidPosttweet (intUseridintTweetid) { if(!Usermap.containskey (userId)) {User U=NewUser (userId); Usermap.put (UserId, u); } usermap.get (UserId). Post (Tweetid); } //Best part of this . //First get all tweets lists from one user including itself and all people it followed. //Second Add all heads to a max heap. Every time we poll a tweet with//largest time stamp from the heap and then we add their next tweet into the heap. //So after adding all heads we have need to add 9 tweets//Heap Before we get the most recent tweets. PublicList<integer> Getnewsfeed (intuserId) {List<Integer> res =NewLinkedlist<>(); if(!usermap.containskey (USERID))returnRes; Set<Integer> users =Usermap.get (userId). followed; Priorityqueue<Tweet> q =NewPriorityqueue<tweet> (Users.size (),NewComparator<tweet>() {@Override Public intCompare (tweet i1, tweet i2) {returnI2.time-I1.time; } }); //(A, B), (B.time-a.time)); for(intuser:users) {Tweet T=usermap.get (user). Tweet_head; //very imporant! If we add null to the head we are screwed. if(t!=NULL) {Q.add (t); } } intN=0; while(!q.isempty () && n<10) {Tweet T=Q.poll (); Res.add (t.id); N++; if(t.next!=NULL) Q.add (T.next); } returnRes; } /**Follower follows a followee. If The operation is invalid, it should be a no-op.*/ Public voidFollow (intFollowerid,intFolloweeid) { if(!Usermap.containskey (Followerid)) {User U=NewUser (Followerid); Usermap.put (Followerid, u); } if(!Usermap.containskey (Followeeid)) {User U=NewUser (Followeeid); Usermap.put (Followeeid, u); } usermap.get (Followerid). Follow (Followeeid); } /**Follower unfollows a followee. If The operation is invalid, it should be a no-op.*/ Public voidUnfollow (intFollowerid,intFolloweeid) { if(!usermap.containskey (followerid) | | followerid==Followeeid)return; Usermap.get (Followerid). Unfollow (Followeeid); } }
355. Design Twitter