| 23 | } |
| 24 | |
| 25 | public List<Integer> getNewsFeed(int userId) { |
| 26 | List<Integer> res = new ArrayList<>(); |
| 27 | |
| 28 | PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> |
| 29 | Integer.compare(b[0], a[0]) |
| 30 | ); |
| 31 | |
| 32 | followerMap.computeIfAbsent(userId, |
| 33 | k -> new HashSet<>() |
| 34 | ); |
| 35 | |
| 36 | followerMap.get(userId).add(userId); |
| 37 | |
| 38 | followerMap.get(userId).forEach((followeeId) -> { |
| 39 | if (tweetMap.containsKey(followeeId)) { |
| 40 | int i = tweetMap.get(followeeId).size() - 1; |
| 41 | int[] tweet = tweetMap.get(followeeId).get(i); |
| 42 | pq.offer(new int[]{tweet[0], tweet[1], |
| 43 | followeeId, --i}); |
| 44 | } |
| 45 | }); |
| 46 | |
| 47 | while (!pq.isEmpty() && res.size() < 10) { |
| 48 | int[] data = pq.poll(); |
| 49 | res.add(data[1]); |
| 50 | |
| 51 | if (data[3] >= 0) { |
| 52 | int[] tweet = tweetMap.get(data[2]).get(data[3]); |
| 53 | pq.offer(new int[]{tweet[0], tweet[1], |
| 54 | data[2], --data[3]}); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | return res; |
| 59 | } |
| 60 | |
| 61 | public void follow(int followerId, int followeeId) { |
| 62 | followerMap.computeIfAbsent(followerId, |