Skip to content

Commit 08e9513

Browse files
committed
fix: update solutin for design twitter
1 parent 69ca2e7 commit 08e9513

File tree

1 file changed

+7
-18
lines changed

1 file changed

+7
-18
lines changed

alternative/medium/design_twitter.py

+7-18
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,43 @@
11
from typing import List
22
import heapq
3+
from collections import defaultdict
34

45
class Twitter:
56

67
def __init__(self):
78
"""
89
Initialize your data structure here.
910
"""
10-
self.tweets = {}
11-
self.follows = {}
11+
self.tweets = defaultdict(list)
12+
self.follows = defaultdict(set)
1213
self.time = 0
1314

1415
def postTweet(self, userId: int, tweetId: int) -> None:
15-
if self.tweets.get(userId) is None:
16-
self.tweets[userId] = []
17-
1816
self.tweets[userId].append([self.time, tweetId])
1917
self.time -= 1
2018

21-
2219
def getNewsFeed(self, userId: int) -> List[int]:
2320
minHeap = []
2421
res = []
2522

26-
if self.follows.get(userId) is None:
27-
self.follows[userId] = set()
28-
2923
self.follows[userId].add(userId)
30-
3124
for followeeId in self.follows[userId]:
3225
if followeeId in self.tweets:
3326
index = len(self.tweets[followeeId]) - 1
3427
count, tweetId = self.tweets[followeeId][index]
35-
minHeap.append([count, tweetId, followeeId, index - 1])
28+
heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])
3629

37-
heapq.heapify(minHeap)
38-
3930
while len(res) < 10 and minHeap:
4031
count, tweetId, followeeId, index = heapq.heappop(minHeap)
4132
res.append(tweetId)
4233
if index >= 0:
43-
count, tweetId, self.tweets[followeeId][index]
34+
count, tweetId = self.tweets[followeeId][index]
4435
heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])
4536

4637
return res
4738

4839

4940
def follow(self, followerId: int, followeeId: int) -> None:
50-
if self.follows.get(followerId) is None:
51-
self.follows[followerId] = set()
52-
5341
self.follows[followerId].add(followeeId)
5442

5543

@@ -68,4 +56,5 @@ def unfollow(self, followerId: int, followeeId: int) -> None:
6856

6957
twitter = Twitter()
7058
twitter.postTweet(1, 5)
71-
assert twitter.getNewsFeed(1) == [5]
59+
twitter.postTweet(1, 3)
60+
assert twitter.getNewsFeed(1) == [3, 5]

0 commit comments

Comments
 (0)