Only use map, list and set, naive approach, easy to understand


  • 0
    W

    public class Twitter {

    public Map<Integer, List<Integer>> userTweets;
    public Map<Integer, Set<Integer>> follows;
    public List<Integer> tweets;
    
    /** Initialize your data structure here. */
    public Twitter() {
        userTweets = new HashMap<Integer, List<Integer>>();
        follows = new HashMap<Integer, Set<Integer>>(); 
        tweets = new ArrayList<Integer>();
    }
    
    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        tweets.add(tweetId);
        if(!userTweets.containsKey(userId))
            userTweets.put(userId, new ArrayList<Integer>());
        userTweets.get(userId).add(tweets.size() - 1);
    }
    
    /** 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> result = new ArrayList<Integer>();
        //prepare userIds and their last index
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        if(follows.containsKey(userId)){
            for(int id : follows.get(userId)){
                if(userTweets.containsKey(id))
                    map.put(id, userTweets.get(id).size() - 1);
            }
        }
        if(userTweets.containsKey(userId))
            map.put(userId, userTweets.get(userId).size() - 1);
        //find top 10
        int count = 0;
        while(count < 10){
            int max = -1;
            int uid = -1;
            for(int id : map.keySet()){
                if(map.get(id) < 0)
                    continue;
                int v = userTweets.get(id).get(map.get(id));
                if(v > max){
                    max = v;
                    uid = id;
                }
            }
            if(max == -1)
                break;
            result.add(tweets.get(max));
            map.put(uid, map.get(uid) - 1);
            count++;
        }
        return result;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        if(!follows.containsKey(followerId))
            follows.put(followerId, new HashSet<Integer>());
        follows.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(follows.containsKey(followerId) && follows.get(followerId).contains(followeeId)){
            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.