One of shortest solutions:


  • 0
    X
    public class Twitter {
        private final Deque<int[]> feeds = new LinkedList<>();
        private final Map<Integer, Set<Integer>> follows = new HashMap<>();
    
        /** Initialize your data structure here. */
        public Twitter() {
        }
     
        public void postTweet(int userId, int tweetId) {
            feeds.addFirst(new int[] { userId, tweetId });
        }
     
        public List<Integer> getNewsFeed(int userId) {
            follows.computeIfAbsent(userId, HashSet::new).add(userId);
            final Set<Integer> followeeIds = follows.get(userId); 
    
            return feeds.stream().filter(f -> followeeIds.contains(f[0])).limit(10).map(f -> f[1]).collect(Collectors.toList());
        }
    
        public void follow(int followerId, int followeeId) {
            follows.computeIfAbsent(followerId, HashSet::new).add(followeeId);
        }
    
        public void unfollow(int followerId, int followeeId) {
            if (follows.containsKey(followerId)) {
                follows.get(followerId).remove(followeeId);
            }
        }
    }
    

Log in to reply
 

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