Skip to content

Commit 10ebd56

Browse files
authored
Create 355-Design-Twitter.py
1 parent 99805d2 commit 10ebd56

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

355-Design-Twitter.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Twitter:
2+
3+
def __init__(self):
4+
self.count = 0
5+
self.tweetMap = defaultdict(list) # userId -> list of [count, tweetIds]
6+
self.followMap = defaultdict(set) # userId -> set of followeeId
7+
8+
def postTweet(self, userId: int, tweetId: int) -> None:
9+
self.tweetMap[userId].append([self.count, tweetId])
10+
self.count -= 1
11+
12+
def getNewsFeed(self, userId: int) -> List[int]:
13+
res = []
14+
minHeap = []
15+
16+
self.followMap[userId].add(userId)
17+
for followeeId in self.followMap[userId]:
18+
if followeeId in self.tweetMap:
19+
index = len(self.tweetMap[followeeId]) - 1
20+
count, tweetId = self.tweetMap[followeeId][index]
21+
heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])
22+
23+
while minHeap and len(res) < 10:
24+
count, tweetId, followeeId, index = heapq.heappop(minHeap)
25+
res.append(tweetId)
26+
if index >= 0:
27+
count, tweetId = self.tweetMap[followeeId][index]
28+
heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])
29+
return res
30+
31+
def follow(self, followerId: int, followeeId: int) -> None:
32+
self.followMap[followerId].add(followeeId)
33+
34+
def unfollow(self, followerId: int, followeeId: int) -> None:
35+
if followeeId in self.followMap[followerId]:
36+
self.followMap[followerId].remove(followeeId)

0 commit comments

Comments
 (0)