-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwitter.java
More file actions
105 lines (92 loc) · 2.56 KB
/
Copy pathTwitter.java
File metadata and controls
105 lines (92 loc) · 2.56 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import java.util.*;
public class Twitter
{
Map<Integer, User> users;
Map<Integer, List<Integer>> userTweets;
Map<Integer, Tweet> tweets;
int time = 0;
public Twitter()
{
users = new HashMap<>();
tweets = new HashMap<>();
userTweets = new HashMap<>();
}
public void postTweet(int userId, int tweetId)
{
users.putIfAbsent(userId, new User(userId));
userTweets.putIfAbsent(userId, new ArrayList<>());
userTweets.get(userId).add(tweetId);
tweets.put(tweetId, new Tweet(tweetId, time));
time++;
}
public List<Integer> getNewsFeed(int userId)
{
if (!users.containsKey(userId))
{
return new ArrayList<>();
}
PriorityQueue<Tweet> queue = new PriorityQueue<>(new Comparator<Tweet>()
{
@Override
public int compare(Tweet o1, Tweet o2)
{
return o2.time - o1.time;
}
});
addToQueue(userId, queue);
for (Integer followeeId : users.get(userId).follows)
{
addToQueue(followeeId, queue);
}
List<Integer> newsFeed = new ArrayList<>();
while (!queue.isEmpty() && newsFeed.size() < 10)
{
newsFeed.add(queue.poll().tweetId);
}
return newsFeed;
}
private void addToQueue(int userId, PriorityQueue<Tweet> queue)
{
for (Integer tweetId : userTweets.getOrDefault(userId, new ArrayList<>()))
{
queue.add(tweets.get(tweetId));
}
}
public void follow(int followerId, int followeeId)
{
if (followerId == followeeId)
{
return;
}
users.putIfAbsent(followerId, new User(followerId));
users.putIfAbsent(followeeId, new User(followeeId));
users.get(followerId).follows.add(followeeId);
}
public void unfollow(int followerId, int followeeId)
{
users.putIfAbsent(followerId, new User(followerId));
users.putIfAbsent(followeeId, new User(followeeId));
users.get(followerId).follows.remove(new Integer(followeeId));
}
class User
{
int userId;
HashSet<Integer> follows = new HashSet<Integer>();
public User(int userId)
{
super();
this.userId = userId;
}
}
class Tweet
{
int tweetId;
int time;
public Tweet(int tweetId, int time)
{
super();
this.tweetId = tweetId;
this.time = time;
}
}
}