Java Solution with two hashMap and one list


  • 0
    Y

    Here I use one global list to store all tweets. When a user wants to get the latest 10 tweets , we scan from the tail of the global list and if it is posted by himself or people he follows we add the tweet to the result.

    public class Twitter {
    //use hash to store each user's follow list
    //the follow list is a hash set
    //easy to unfollow
    private Map<Integer,Set<Integer>> followStatus;

    //save all tweets
    private List<Integer> tweets;
    
    //save tweetId-UserId pair
    private Map<Integer,Integer> tweetUser;
    
    /** Initialize your data structure here. */
    public Twitter() {
        this.followStatus = new HashMap<>();
        this.tweets = new ArrayList<>();
        this.tweetUser = new HashMap<>();
    }
    
    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        tweets.add(tweetId);
        tweetUser.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> recent = new ArrayList<>();
        int index = tweets.size()-1;
        while(recent.size() < 10 && index >= 0){
            int curTweet = tweets.get(index);
            int curUser = tweetUser.get(curTweet);
            Set<Integer> curFollow = followStatus.get(userId);
            
            if(curUser == userId || (curFollow != null && curFollow.contains(curUser))){
                recent.add(curTweet);
            }
            
            index--;
        }
        return recent;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        Set<Integer> curFollow = followStatus.getOrDefault(followerId,new HashSet<>());
        curFollow.add(followeeId);
        followStatus.put(followerId,curFollow);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
        if(followStatus.containsKey(followerId)){
            Set<Integer> curFollow = followStatus.get(followerId);
            curFollow.remove(followeeId);
            followStatus.put(followerId,curFollow);
        }
    }
    

    }

    /**

    • Your Twitter object will be instantiated and called as such:
    • Twitter obj = new Twitter();
    • obj.postTweet(userId,tweetId);
    • List<Integer> param_2 = obj.getNewsFeed(userId);
    • obj.follow(followerId,followeeId);
    • obj.unfollow(followerId,followeeId);
      */

Log in to reply
 

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