Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Twitter {
- // timestamp is incremented each time we have new tweet
- int timestamp;
- // stores tweetId and userId of tweet which was done at timestamp
- ArrayList<ArrayList<Integer>> tweet_with_timestamp;
- // stores userIds which a user follows
- Map<Integer, Set<Integer>> follow;
- // stores timestamps of tweets done by a user
- Map<Integer, ArrayList<Integer>> tweet;
- public Twitter()
- {
- this.timestamp = 0;
- this.tweet_with_timestamp = new ArrayList<ArrayList<Integer>> ();
- this.follow = new HashMap<Integer, Set<Integer>> ();
- this.tweet = new HashMap<Integer, ArrayList<Integer>> ();
- }
- public void postTweet(int userId, int tweetId)
- {
- tweet.putIfAbsent(userId, new ArrayList<Integer> ());
- tweet.get(userId).add(timestamp);
- tweet_with_timestamp.add(new ArrayList<Integer> (List.of(tweetId, userId)) );
- timestamp++;
- }
- public List<Integer> getNewsFeed(int userId)
- {
- // Adding user to its list of followees
- // This will allow us to consider tweets done by the user itself
- follow.putIfAbsent(userId, new HashSet<Integer>());
- follow.get(userId).add(userId);
- // pointer stores the position of the most recent tweet done by a followee
- Map<Integer, Integer> pointer = new HashMap<Integer, Integer> ();
- // priority queue stores the timestamp of the most recent tweet done by each followee
- PriorityQueue<Integer> pq = new PriorityQueue<Integer> (Collections.reverseOrder());
- for(Integer followeeId: follow.get(userId))
- {
- if(tweet.containsKey(followeeId))
- {
- int p = tweet.get(followeeId).size() - 1;
- pointer.put(followeeId, p);
- pq.add(tweet.get(followeeId).get(p));
- }
- }
- ArrayList<Integer> NewsFeed = new ArrayList<Integer> ();
- for(int i = 0; i < 10 && !pq.isEmpty(); i++)
- {
- int t = pq.poll(); // timestamp of most recent tweet
- int tweetId = tweet_with_timestamp.get(t).get(0);
- int tweetUserId = tweet_with_timestamp.get(t).get(1);
- NewsFeed.add(tweetId);
- int p = pointer.get(tweetUserId);
- if(p > 0)
- {
- // Adding the timestamp of the next most recent tweet done by the tweetUser in priority queue
- pointer.put(tweetUserId, p-1);
- pq.add(tweet.get(tweetUserId).get(p-1));
- }
- }
- return NewsFeed;
- }
- public void follow(int followerId, int followeeId)
- {
- follow.putIfAbsent(followerId, new HashSet<Integer>());
- follow.get(followerId).add(followeeId);
- }
- public void unfollow(int followerId, int followeeId)
- {
- if(follow.containsKey(followerId)) {
- follow.get(followerId).remove(followeeId);
- }
- }
- }
Add Comment
Please, Sign In to add comment