Java only use one map and one list -slow but very easy to understand


  • 0
    G
    class tInfor{
        int userId;
        int tweetId;
        tInfor(int userId, int tweetId){
            this.userId = userId;
            this.tweetId = tweetId;
        }
        
    }
    public class Twitter {
        HashMap<Integer,ArrayList<Integer>> folo;
        ArrayList<tInfor> list;
        
        /** Initialize your data structure here. */
        public Twitter() {
            folo = new HashMap<Integer,ArrayList<Integer>>();
            list = new ArrayList<>();
        }
        
        /** Compose a new tweet. */
        public void postTweet(int userId, int tweetId) {
            tInfor tweet =new tInfor(userId,tweetId);
            list.add(tweet);
        }
        
        /** 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>();
            int len = list.size();
            ArrayList<Integer> friends = folo.get(userId);
            for(int i=len-1; i>=0; i--){
                tInfor temp = list.get(i);
                int fuserId = temp.userId;
                if(friends==null){
                	if(fuserId==userId){
                        res.add(temp.tweetId);
                        if(res.size()>9){
                            return res;
                        }
                    }
                }
                else if (fuserId==userId || friends.contains(fuserId)){
                    res.add(temp.tweetId);
                    if(res.size()>9){
                        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(folo.containsKey(followerId)){
                folo.get(followerId).add(followeeId);
            } else{
                ArrayList<Integer> as = new ArrayList<>();
                as.add(followeeId);
                folo.put(followerId, as);
            }
        }
        
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        public void unfollow(int followerId, int followeeId) {
            if(folo.isEmpty()){
        		return;
        	}
            if(folo.containsKey(followerId)){
                folo.get(followerId).remove((Integer)followeeId);
            }
        }
    }

Log in to reply
 

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