-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution355.cs
68 lines (57 loc) · 1.83 KB
/
Solution355.cs
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
using System.Text;
namespace LeetCode.Solutions;
public class Solution355
{
/// <summary>
/// 355. Design Twitter - Medium
/// <a href="https://leetcode.com/problems/design-twitter">See the problem</a>
/// </summary>
public class Twitter
{
private readonly Dictionary<int, HashSet<int>> _followers = [];
private readonly Dictionary<int, List<(int TweetId, int Time)>> _tweets = [];
private int _time;
public void PostTweet(int userId, int tweetId)
{
if (!_tweets.ContainsKey(userId))
{
_tweets[userId] = [];
}
_tweets[userId].Add((tweetId, _time++));
}
public IList<int> GetNewsFeed(int userId)
{
var tweets = new List<(int TweetId, int Time)>();
if (_tweets.ContainsKey(userId))
{
tweets.AddRange(_tweets[userId]);
}
if (_followers.ContainsKey(userId))
{
foreach (var follower in _followers[userId])
{
if (_tweets.ContainsKey(follower))
{
tweets.AddRange(_tweets[follower]);
}
}
}
return tweets.OrderByDescending(t => t.Time).Take(10).Select(t => t.TweetId).ToList();
}
public void Follow(int followerId, int followeeId)
{
if (!_followers.ContainsKey(followerId))
{
_followers[followerId] = [];
}
_followers[followerId].Add(followeeId);
}
public void Unfollow(int followerId, int followeeId)
{
if (_followers.ContainsKey(followerId))
{
_followers[followerId].Remove(followeeId);
}
}
}
}