JAVA OOD


  • 0
    E
    public class Twitter {
        // map to record follower and followee
        // pair.left stores posterId, pair.right stores postedInfo
        // put all news to a list
    
        private Map<Integer, Set<Integer>> follow;
        private List<Pair> news;
        private static class Pair {
            int left;
            int right;
            public Pair(int left, int right) {
                this.left = left;
                this.right = right;
            }
        }
        
        /** Initialize your data structure here. */
        public Twitter() {
            follow = new HashMap<>();
            news = new ArrayList<>();
        }
        
        /** Compose a new tweet. */
        public void postTweet(int userId, int tweetId) {
            news.add(new Pair(userId, tweetId));
            return;
        }
        
        /** 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) {
            int count = 0;
            List<Integer> res = new ArrayList<>();
            for (int i = news.size() - 1; i >= 0; i--) {
                if (news.get(i).left == userId || (follow.get(userId) != null && follow.get(userId).contains(news.get(i).left))) {
                    res.add(news.get(i).right);
                    count++;
                    if (count == 10) {
                        return res;
                    }
                }
            }
            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 (!follow.containsKey(followerId)) {
                follow.put(followerId, new HashSet<>());
            } 
            follow.get(followerId).add(followeeId);
            return;
        }
        
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        public void unfollow(int followerId, int followeeId) {
            Set<Integer> tmp = follow.get(followerId);
            if (tmp != null && tmp.contains(followeeId)) {
                tmp.remove(followeeId);
            }
            return;
        }
    }
    

Log in to reply
 

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