237 ms java solution


  • 0
    Z
    public class Twitter {
    
    HashMap<Integer, Set<Integer>> maps = new HashMap<Integer, Set<Integer>>();
    List<Feed> feeds = new ArrayList<Feed>();
    
    class Feed {
    	int userId, tweetId;
    
    	public Feed(int userId, int tweetId) {
    		this.userId = userId;
    		this.tweetId = tweetId;
    	}
    	
    	public String toString(){
    		return tweetId+"";
    	}
    }
    
    /** Initialize your data structure here. */
    public Twitter() {
    
    }
    
    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
    	Feed f = new Feed(userId, tweetId);
    	feeds.add(f);
    }
    
    /**
     * 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>();
    	Set<Integer> users = maps.get(userId);
    	if(users==null)
    		users=  new HashSet<Integer>();
    	users.add(userId);
    	for (int i=feeds.size()-1;i>=0;i--) {
    		Feed f = feeds.get(i);
    		if (res.size()<10&&users.contains(f.userId)) {
    			res.add(f.tweetId);
    		}
    		if(res.size()>=10)
    			break;
    	}
    	return res;
    }
    
    /**
     * Follower follows a followee. If the operation is invalid, it should be a
     * no-op.
     */
    public void follow(int followerId, int followeeId) {
    	Set<Integer> sets;
    	if (maps.containsKey(followerId)) {
    		sets = maps.get(followerId);
    	} else {
    		sets = new HashSet<Integer>();
    	}
    	sets.add(followeeId);
    	maps.put(followerId, sets);
    }
    
    /**
     * Follower unfollows a followee. If the operation is invalid, it should be
     * a no-op.
     */
    public void unfollow(int followerId, int followeeId) {
    	Set<Integer> sets = maps.get(followerId);
    	if(sets!=null&&sets.contains(followeeId)){
    		sets.remove(followeeId);
    		maps.put(followerId, sets);
    	}
    }
    

    }

    /**

    • 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.