-
Notifications
You must be signed in to change notification settings - Fork 0
/
designtwitter.py
51 lines (41 loc) · 1.64 KB
/
designtwitter.py
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
from collections import defaultdict
import heapq
class Twitter:
def __init__(self):
self.count = 0
self.tweetMap = defaultdict(list)
self.followMap = defaultdict(set)
def postTweet(self, userId: int, tweetId: int) -> None:
self.tweetMap[userId].append([self.count, tweetId])
self.count -= 1
def getNewsFeed(self, userId: int):
res = []
minHeap = []
self.followMap[userId].add(userId)
for followeeId in self.followMap[userId]:
if followeeId in self.tweetMap:
index = len(self.tweetMap[followeeId]) - 1
count, tweetId = self.tweetMap[followeeId][index]
minHeap.append([count, tweetId, followeeId, index - 1])
heapq.heapify(minHeap)
while minHeap and len(res) < 10:
count, tweetId, followeeId, index = heapq.heappop(minHeap)
res.append(tweetId)
if index >= 0:
count, tweetId = self.tweetMap[followeeId][index]
heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])
return res
def follow(self, followerId: int, followeeId: int) -> None:
self.followMap[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
if followeeId in self.followMap[followerId]:
self.followMap[followerId].remove(followeeId)
# Your Twitter object will be instantiated and called as such:
obj = Twitter()
print(obj.postTweet(1, 5))
print(obj.getNewsFeed(1))
print(obj.follow(1, 2))
print(obj.postTweet(2, 6))
print(obj.getNewsFeed(1))
print(obj.unfollow(1, 2))
print(obj.getNewsFeed(1))