Simple Java Solution using HashMap


  • 0
    D
    public class Twitter {
        
        class tweet{
            int id;
            int time;
            public tweet(int id,int time){
                this.id=id;this.time=time;
            }
        }
        Map<Integer,Set<Integer>> fans;
        Map<Integer,List<tweet>> tweets;
        int count=0;
        /** Initialize your data structure here. */
        public Twitter() {
            fans=new HashMap<>();
            tweets=new HashMap<>();
        }
        
        /** Compose a new tweet. */
        public void postTweet(int userId, int tweetId) {
            if(!fans.containsKey(userId)) fans.put(userId,new HashSet<>());
            fans.get(userId).add(userId);
            if(!tweets.containsKey(userId)) tweets.put(userId,new LinkedList<>());
            tweets.get(userId).add(new tweet(tweetId,count++));
        }
        
        /** 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) {
            if(!fans.containsKey(userId)) return new LinkedList<>();
            PriorityQueue<tweet> feed=new PriorityQueue<>((t1,t2) -> t2.time-t1.time);
            fans.get(userId).stream().filter(f->tweets.containsKey(f)).forEach(f->tweets.get(f).forEach(feed::add));
            List<Integer> list=new LinkedList<>();
            while(feed.size()>0&&list.size()<10) list.add(feed.poll().id);
            return list;
        }
        
        /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
        public void follow(int followerId, int followeeId) {
            if(!fans.containsKey(followerId)) fans.put(followerId,new HashSet<>());
            fans.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(!fans.containsKey(followerId)) fans.put(followerId,new HashSet<>());
            if(followerId==followeeId) return ;
            fans.get(followerId).remove(followeeId);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.