Simple Java Solution


  • 0
    R
    import java.util.LinkedHashMap;
    

    public class Twitter {
    HashMap<Integer, Set<Integer>> map;
    LinkedHashMap<Integer, Integer> feeds;
    /**
    * Initialize your data structure here.
    */
    public Twitter() {
    map = new HashMap<>();
    feeds = new LinkedHashMap<>();
    }

    /**
     * Compose a new tweet.
     */
    public void postTweet(int userId, int tweetId) {
            if (!map.containsKey(userId))
                map.put(userId, new HashSet<>());
            feeds.put(tweetId, userId);
    }
    
    /**
     * 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) {
        List<Integer> res = new ArrayList<Integer>();
        if (!map.containsKey(userId))
            return res;
        Set<Integer> followerSet = map.get(userId);
        LinkedList<Map.Entry<Integer,Integer>> rev = new LinkedList<>(feeds.entrySet());
        Iterator<Map.Entry<Integer,Integer>> revIterator = rev.descendingIterator();
        int count = 10;
        while (revIterator.hasNext()&&count>0){
            Map.Entry<Integer,Integer> e = revIterator.next();
            if (followerSet.contains(e.getValue()) || e.getValue()==userId){
                res.add(e.getKey());
                count--;
            }
        }
        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 (!map.containsKey(followerId))
            map.put(followerId, new HashSet<>());
        map.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 (map.containsKey(followerId)){
            Set<Integer> set  = map.get(followerId);
            if (set.contains(followeeId)){
                set.remove(followeeId);
            }
        }
    }
    

    // public static void main(String[] args) {
    // Twitter twitter = new Twitter();
    // twitter.postTweet(1,5);
    // System.out.println(twitter.getNewsFeed(1));
    // twitter.follow(1,2);
    // twitter.postTweet(2,6);
    // System.out.println(twitter.getNewsFeed(1));
    // twitter.unfollow(1,2);
    // System.out.println(twitter.getNewsFeed(1));
    // }
    }


Log in to reply
 

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