Skip to content

Commit 293ddf8

Browse files
committed
feat: add solutions to leetcode problem: No.0355. Design Twitter
1 parent eaa73c2 commit 293ddf8

File tree

4 files changed

+333
-61
lines changed

4 files changed

+333
-61
lines changed

Diff for: solution/0300-0399/0355.Design Twitter/README.md

+120-3
Original file line numberDiff line numberDiff line change
@@ -44,27 +44,144 @@ twitter.unfollow(1, 2);
4444
twitter.getNewsFeed(1);
4545
</pre>
4646

47-
4847
## 解法
4948

5049
<!-- 这里可写通用的实现逻辑 -->
5150

51+
“哈希表 + 堆”实现。
52+
5253
<!-- tabs:start -->
5354

5455
### **Python3**
5556

5657
<!-- 这里可写当前语言的特殊实现逻辑 -->
5758

5859
```python
59-
60+
class Twitter:
61+
62+
def __init__(self):
63+
"""
64+
Initialize your data structure here.
65+
"""
66+
self.user_tweets = collections.defaultdict(list)
67+
self.user_following = collections.defaultdict(set)
68+
self.tweets = collections.defaultdict()
69+
self.time = 0
70+
71+
def postTweet(self, userId: int, tweetId: int) -> None:
72+
"""
73+
Compose a new tweet.
74+
"""
75+
self.time += 1
76+
self.user_tweets[userId].append(tweetId)
77+
self.tweets[tweetId] = self.time
78+
79+
def getNewsFeed(self, userId: int) -> List[int]:
80+
"""
81+
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
82+
"""
83+
following = self.user_following[userId]
84+
users = set(following)
85+
users.add(userId)
86+
tweets = [self.user_tweets[u][::-1][:10] for u in users]
87+
tweets = sum(tweets, [])
88+
return heapq.nlargest(10, tweets, key=lambda tweet: self.tweets[tweet])
89+
90+
def follow(self, followerId: int, followeeId: int) -> None:
91+
"""
92+
Follower follows a followee. If the operation is invalid, it should be a no-op.
93+
"""
94+
self.user_following[followerId].add(followeeId)
95+
96+
def unfollow(self, followerId: int, followeeId: int) -> None:
97+
"""
98+
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
99+
"""
100+
following = self.user_following[followerId]
101+
if followeeId in following:
102+
following.remove(followeeId)
103+
104+
105+
106+
# Your Twitter object will be instantiated and called as such:
107+
# obj = Twitter()
108+
# obj.postTweet(userId,tweetId)
109+
# param_2 = obj.getNewsFeed(userId)
110+
# obj.follow(followerId,followeeId)
111+
# obj.unfollow(followerId,followeeId)
60112
```
61113

62114
### **Java**
63115

64116
<!-- 这里可写当前语言的特殊实现逻辑 -->
65117

66118
```java
67-
119+
class Twitter {
120+
private Map<Integer, List<Integer>> userTweets;
121+
private Map<Integer, Set<Integer>> userFollowing;
122+
private Map<Integer, Integer> tweets;
123+
private int time;
124+
125+
/** Initialize your data structure here. */
126+
public Twitter() {
127+
userTweets = new HashMap<>();
128+
userFollowing = new HashMap<>();
129+
tweets = new HashMap<>();
130+
time = 0;
131+
}
132+
133+
/** Compose a new tweet. */
134+
public void postTweet(int userId, int tweetId) {
135+
List<Integer> userTweet = userTweets.getOrDefault(userId, new ArrayList<>());
136+
userTweet.add(tweetId);
137+
userTweets.put(userId, userTweet);
138+
tweets.put(tweetId, ++time);
139+
}
140+
141+
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
142+
public List<Integer> getNewsFeed(int userId) {
143+
Set<Integer> following = userFollowing.getOrDefault(userId, new HashSet<>());
144+
Set<Integer> users = new HashSet<>(following);
145+
users.add(userId);
146+
PriorityQueue<Integer> pq = new PriorityQueue<>(10, (a, b) -> (tweets.get(b) - tweets.get(a)));
147+
for (Integer u : users) {
148+
List<Integer> userTweet = userTweets.get(u);
149+
if (userTweet != null && !userTweet.isEmpty()) {
150+
for (int i = userTweet.size() - 1, k = 10; i >= 0 && k > 0; --i, --k) {
151+
pq.offer(userTweet.get(i));
152+
}
153+
}
154+
}
155+
List<Integer> res = new ArrayList<>();
156+
while (!pq.isEmpty() && res.size() < 10) {
157+
res.add(pq.poll());
158+
}
159+
return res;
160+
}
161+
162+
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
163+
public void follow(int followerId, int followeeId) {
164+
Set<Integer> following = userFollowing.getOrDefault(followerId, new HashSet<>());
165+
following.add(followeeId);
166+
userFollowing.put(followerId, following);
167+
}
168+
169+
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
170+
public void unfollow(int followerId, int followeeId) {
171+
Set<Integer> following = userFollowing.getOrDefault(followerId, new HashSet<>());
172+
following.remove(followeeId);
173+
userFollowing.put(followerId, following);
174+
}
175+
}
176+
177+
/**
178+
* Your Twitter object will be instantiated and called as such:
179+
* Twitter obj = new Twitter();
180+
* obj.postTweet(userId,tweetId);
181+
* List<Integer> param_2 = obj.getNewsFeed(userId);
182+
* obj.follow(followerId,followeeId);
183+
* obj.unfollow(followerId,followeeId);
184+
*/
68185
```
69186

70187
### **...**

Diff for: solution/0300-0399/0355.Design Twitter/README_EN.md

+118-3
Original file line numberDiff line numberDiff line change
@@ -47,21 +47,136 @@ twitter.getNewsFeed(1); // User 1&#39;s news feed should return a list with 1 t
4747
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>postTweet</code>, <code>getNewsFeed</code>, <code>follow</code>, and <code>unfollow</code>.</li>
4848
</ul>
4949

50-
5150
## Solutions
5251

5352
<!-- tabs:start -->
5453

5554
### **Python3**
5655

5756
```python
58-
57+
class Twitter:
58+
59+
def __init__(self):
60+
"""
61+
Initialize your data structure here.
62+
"""
63+
self.user_tweets = collections.defaultdict(list)
64+
self.user_following = collections.defaultdict(set)
65+
self.tweets = collections.defaultdict()
66+
self.time = 0
67+
68+
def postTweet(self, userId: int, tweetId: int) -> None:
69+
"""
70+
Compose a new tweet.
71+
"""
72+
self.time += 1
73+
self.user_tweets[userId].append(tweetId)
74+
self.tweets[tweetId] = self.time
75+
76+
def getNewsFeed(self, userId: int) -> List[int]:
77+
"""
78+
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
79+
"""
80+
following = self.user_following[userId]
81+
users = set(following)
82+
users.add(userId)
83+
tweets = [self.user_tweets[u][::-1][:10] for u in users]
84+
tweets = sum(tweets, [])
85+
return heapq.nlargest(10, tweets, key=lambda tweet: self.tweets[tweet])
86+
87+
def follow(self, followerId: int, followeeId: int) -> None:
88+
"""
89+
Follower follows a followee. If the operation is invalid, it should be a no-op.
90+
"""
91+
self.user_following[followerId].add(followeeId)
92+
93+
def unfollow(self, followerId: int, followeeId: int) -> None:
94+
"""
95+
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
96+
"""
97+
following = self.user_following[followerId]
98+
if followeeId in following:
99+
following.remove(followeeId)
100+
101+
102+
103+
# Your Twitter object will be instantiated and called as such:
104+
# obj = Twitter()
105+
# obj.postTweet(userId,tweetId)
106+
# param_2 = obj.getNewsFeed(userId)
107+
# obj.follow(followerId,followeeId)
108+
# obj.unfollow(followerId,followeeId)
59109
```
60110

61111
### **Java**
62112

63113
```java
64-
114+
class Twitter {
115+
private Map<Integer, List<Integer>> userTweets;
116+
private Map<Integer, Set<Integer>> userFollowing;
117+
private Map<Integer, Integer> tweets;
118+
private int time;
119+
120+
/** Initialize your data structure here. */
121+
public Twitter() {
122+
userTweets = new HashMap<>();
123+
userFollowing = new HashMap<>();
124+
tweets = new HashMap<>();
125+
time = 0;
126+
}
127+
128+
/** Compose a new tweet. */
129+
public void postTweet(int userId, int tweetId) {
130+
List<Integer> userTweet = userTweets.getOrDefault(userId, new ArrayList<>());
131+
userTweet.add(tweetId);
132+
userTweets.put(userId, userTweet);
133+
tweets.put(tweetId, ++time);
134+
}
135+
136+
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
137+
public List<Integer> getNewsFeed(int userId) {
138+
Set<Integer> following = userFollowing.getOrDefault(userId, new HashSet<>());
139+
Set<Integer> users = new HashSet<>(following);
140+
users.add(userId);
141+
PriorityQueue<Integer> pq = new PriorityQueue<>(10, (a, b) -> (tweets.get(b) - tweets.get(a)));
142+
for (Integer u : users) {
143+
List<Integer> userTweet = userTweets.get(u);
144+
if (userTweet != null && !userTweet.isEmpty()) {
145+
for (int i = userTweet.size() - 1, k = 10; i >= 0 && k > 0; --i, --k) {
146+
pq.offer(userTweet.get(i));
147+
}
148+
}
149+
}
150+
List<Integer> res = new ArrayList<>();
151+
while (!pq.isEmpty() && res.size() < 10) {
152+
res.add(pq.poll());
153+
}
154+
return res;
155+
}
156+
157+
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
158+
public void follow(int followerId, int followeeId) {
159+
Set<Integer> following = userFollowing.getOrDefault(followerId, new HashSet<>());
160+
following.add(followeeId);
161+
userFollowing.put(followerId, following);
162+
}
163+
164+
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
165+
public void unfollow(int followerId, int followeeId) {
166+
Set<Integer> following = userFollowing.getOrDefault(followerId, new HashSet<>());
167+
following.remove(followeeId);
168+
userFollowing.put(followerId, following);
169+
}
170+
}
171+
172+
/**
173+
* Your Twitter object will be instantiated and called as such:
174+
* Twitter obj = new Twitter();
175+
* obj.postTweet(userId,tweetId);
176+
* List<Integer> param_2 = obj.getNewsFeed(userId);
177+
* obj.follow(followerId,followeeId);
178+
* obj.unfollow(followerId,followeeId);
179+
*/
65180
```
66181

67182
### **...**

0 commit comments

Comments
 (0)