Skip to main content

355. Design Twitter

link

  • Use set to record follow status
  • Use list to record post
  • When get newsfeed, just get every list last record and compare(like merge k list)
class Twitter:

def __init__(self):
self.time = 0
self.P = defaultdict(list)
self.C = defaultdict(set)



def postTweet(self, userId: int, tweetId: int) -> None:
self.P[userId].append((self.time,tweetId))
self.time += 1


def getNewsFeed(self, userId: int) -> List[int]:
arr = []

for followeeId in self.C[userId]:
arr += self.P[followeeId][-10:]

arr += self.P[userId][-10:]

return [ t[1] for t in nlargest(10, arr)]


def follow(self, followerId: int, followeeId: int) -> None:
self.C[followerId].add(followeeId)


def unfollow(self, followerId: int, followeeId: int) -> None:
if followeeId in self.C[followerId]:
self.C[followerId].remove(followeeId)