1
1
from typing import List
2
2
import heapq
3
+ from collections import defaultdict
3
4
4
5
class Twitter :
5
6
6
7
def __init__ (self ):
7
8
"""
8
9
Initialize your data structure here.
9
10
"""
10
- self .tweets = {}
11
- self .follows = {}
11
+ self .tweets = defaultdict ( list )
12
+ self .follows = defaultdict ( set )
12
13
self .time = 0
13
14
14
15
def postTweet (self , userId : int , tweetId : int ) -> None :
15
- if self .tweets .get (userId ) is None :
16
- self .tweets [userId ] = []
17
-
18
16
self .tweets [userId ].append ([self .time , tweetId ])
19
17
self .time -= 1
20
18
21
-
22
19
def getNewsFeed (self , userId : int ) -> List [int ]:
23
20
minHeap = []
24
21
res = []
25
22
26
- if self .follows .get (userId ) is None :
27
- self .follows [userId ] = set ()
28
-
29
23
self .follows [userId ].add (userId )
30
-
31
24
for followeeId in self .follows [userId ]:
32
25
if followeeId in self .tweets :
33
26
index = len (self .tweets [followeeId ]) - 1
34
27
count , tweetId = self .tweets [followeeId ][index ]
35
- minHeap . append ( [count , tweetId , followeeId , index - 1 ])
28
+ heapq . heappush ( minHeap , [count , tweetId , followeeId , index - 1 ])
36
29
37
- heapq .heapify (minHeap )
38
-
39
30
while len (res ) < 10 and minHeap :
40
31
count , tweetId , followeeId , index = heapq .heappop (minHeap )
41
32
res .append (tweetId )
42
33
if index >= 0 :
43
- count , tweetId , self .tweets [followeeId ][index ]
34
+ count , tweetId = self .tweets [followeeId ][index ]
44
35
heapq .heappush (minHeap , [count , tweetId , followeeId , index - 1 ])
45
36
46
37
return res
47
38
48
39
49
40
def follow (self , followerId : int , followeeId : int ) -> None :
50
- if self .follows .get (followerId ) is None :
51
- self .follows [followerId ] = set ()
52
-
53
41
self .follows [followerId ].add (followeeId )
54
42
55
43
@@ -68,4 +56,5 @@ def unfollow(self, followerId: int, followeeId: int) -> None:
68
56
69
57
twitter = Twitter ()
70
58
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