0%

leetCode-335:Design Twitter

问题描述

要求实现一个简单版的 Twitter。题目链接:**点我**

样例输入输出

输入:

[“Twitter”, “postTweet”, “getNewsFeed”, “follow”, “postTweet”, “getNewsFeed”, “unfollow”, “getNewsFeed”]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

输出:

[null, null, [5], null, null, [6, 5], null, [5]]

解释:

Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1); // User 1’s news feed should return a list with 1 tweet id -> [5]. return [5]
twitter.follow(1, 2); // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1); // User 1’s news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2); // User 1 unfollows user 2.
twitter.getNewsFeed(1); // User 1’s news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.

问题解法

此题是设计类型的题目,只要按要求实现即可。代码如下

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
class Twitter {
class Tweet {
private int tweetId;
private int userId;

public Tweet(int tweetId, int userId) {
this.tweetId = tweetId;
this.userId = userId;
}

public int getTweetId() {
return tweetId;
}

public int getUserId() {
return userId;
}
}

private List<Tweet> tweets = new LinkedList<>();

private Map<Integer, Set<Integer>> followMap = new HashMap<>();

public Twitter() {

}

public void postTweet(int userId, int tweetId) {
tweets.add(0, new Tweet(tweetId, userId));
}

public List<Integer> getNewsFeed(int userId) {
Set<Integer> followSet = followMap.getOrDefault(userId, new HashSet<>());
List<Integer> result = new ArrayList<>(10);
int count = 0;
for (Tweet tweet : tweets) {
int tweetUserId = tweet.getUserId();
if (tweetUserId == userId || followSet.contains(tweetUserId)) {
result.add(tweet.getTweetId());
count++;
if (count == 10) {
break;
}
}
}

return result;
}

public void follow(int followerId, int followeeId) {
Set<Integer> followSet = followMap.getOrDefault(followerId, new HashSet<>());
followSet.add(followeeId);
followMap.put(followerId, followSet);
}

public void unfollow(int followerId, int followeeId) {
Set<Integer> followSet = followMap.getOrDefault(followerId, new HashSet<>());
followSet.remove(followeeId);
}
}

/**
* Your Twitter object will be instantiated and called as such:
* Twitter obj = new Twitter();
* obj.postTweet(userId,tweetId);
* List<Integer> param_2 = obj.getNewsFeed(userId);
* obj.follow(followerId,followeeId);
* obj.unfollow(followerId,followeeId);
*/