-
Notifications
You must be signed in to change notification settings - Fork 21k
Expand file tree
/
Copy pathDesignTwitter.java
More file actions
76 lines (62 loc) · 2.15 KB
/
DesignTwitter.java
File metadata and controls
76 lines (62 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.*;
class Twitter {
private static int timeStamp = 0;
private static class Tweet {
int id;
int time;
Tweet next;
public Tweet(int id, int time) {
this.id = id;
this.time = time;
}
}
private Map<Integer, Set<Integer>> followMap;
private Map<Integer, Tweet> tweetMap;
public Twitter() {
followMap = new HashMap<>();
tweetMap = new HashMap<>();
}
/** User posts a new tweet */
public void postTweet(int userId, int tweetId) {
Tweet newTweet = new Tweet(tweetId, timeStamp++);
if (tweetMap.containsKey(userId)) {
newTweet.next = tweetMap.get(userId);
}
tweetMap.put(userId, newTweet);
}
/** Retrieve the 10 most recent tweet ids in the user's news feed */
public List<Integer> getNewsFeed(int userId) {
List<Integer> result = new ArrayList<>();
// Min-heap to get most recent tweets first
PriorityQueue<Tweet> pq = new PriorityQueue<>((a, b) -> b.time - a.time);
// Add own tweets
if (tweetMap.containsKey(userId)) {
pq.offer(tweetMap.get(userId));
}
// Add followees' tweets
if (followMap.containsKey(userId)) {
for (int followee : followMap.get(userId)) {
if (tweetMap.containsKey(followee)) {
pq.offer(tweetMap.get(followee));
}
}
}
// Retrieve top 10 tweets
while (!pq.isEmpty() && result.size() < 10) {
Tweet t = pq.poll();
result.add(t.id);
if (t.next != null) pq.offer(t.next);
}
return result;
}
public void follow(int followerId, int followeeId) {
if (followerId == followeeId) return; // can’t follow self
followMap.putIfAbsent(followerId, new HashSet<>());
followMap.get(followerId).add(followeeId);
}
/** Follower unfollows a followee */
public void unfollow(int followerId, int followeeId) {
if (!followMap.containsKey(followerId)) return;
followMap.get(followerId).remove(followeeId);
}
}