18 lines Java beats 85%


  • 0
    W
    This post is deleted!

  • -1
    W

    Readable version

    public class Twitter {
      int now = 0;
      Map<Integer, User> userMap = new HashMap<>();
     
      public void postTweet(int userId, int tweetId) {
        userMap.computeIfAbsent(userId, k -> new User()).tweets.add(new Tweet(tweetId));
      }
    
      public List<Integer> getNewsFeed(int userId) {
        List<Integer> result = new ArrayList<>();
        Queue<Entry<List<Tweet>, Integer>> queue = new PriorityQueue<>((e1, e2) -> e2.getKey().get(e2.getValue()).time - e1.getKey().get(e1.getValue()).time);
        add(queue, userMap.computeIfAbsent(userId, k -> new User()).tweets);
        userMap.get(userId).followees.stream().map(id -> userMap.computeIfAbsent(id, k -> new User()).tweets).forEach(tweets -> add(queue, tweets));
        for (int x = 10; x-- > 0 && !queue.isEmpty();) {
          Entry<List<Tweet>, Integer> entry = queue.poll();
          result.add(entry.getKey().get(entry.getValue()).id);
          if (entry.getValue() > 0) {
            entry.setValue(entry.getValue() - 1);
            queue.add(entry);
          }
        }
        return result;
      }
    
      public void follow(int followerId, int followeeId) {
        if (followeeId != followerId) userMap.computeIfAbsent(followerId, k -> new User()).followees.add(followeeId);
      }
        
      public void unfollow(int followerId, int followeeId) {
        userMap.computeIfAbsent(followerId, k -> new User()).followees.remove(followeeId);
      }
    
      private void add(Queue<Entry<List<Tweet>, Integer>> queue, List<Tweet> tweets) {
        if (tweets.size() > 0) queue.add(new SimpleEntry<>(tweets, tweets.size() - 1));
      }
      class User {
        Set<Integer> followees = new HashSet<>();
        List<Tweet> tweets = new ArrayList<>();
      }
      class Tweet {
        int id, time = now++;
        public Tweet(int id) {
          this.id = id;
        }
      }
    }

Log in to reply
 

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