355. Design Twitter

https://leetcode.com/problems/design-twitter/

solution

class User:
    def __init__(self, userId):
        self.userId = userId
        self.tweets = []
        self.followers = set()
        self.follows = set()

class Twitter:
    def __init__(self):
        self.users = dict()
        self.time = 0

    def create_new_user(self, userId):
        if userId not in self.users:
            self.users[userId] = User(userId)

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

    def getNewsFeed(self, userId: int) -> List[int]:
        self.create_new_user(userId)
        aggregated_tweets = list(self.users[userId].tweets)

        for followee in self.users[userId].follows:
            aggregated_tweets.extend(followee.tweets)

        aggregated_tweets.sort(key = lambda x: x[0], reverse=True)
        feed = [tweet[1] for tweet in aggregated_tweets[:10]]
        return feed

    def follow(self, followerId: int, followeeId: int) -> None:
        self.create_new_user(followerId)
        self.create_new_user(followeeId)
        self.users[followerId].follows.add(self.users[followeeId])
        self.users[followeeId].followers.add(self.users[followerId])

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.create_new_user(followerId)
        self.create_new_user(followeeId)

        if self.users[followerId] in self.users[followeeId].followers:
            self.users[followeeId].followers.remove(self.users[followerId])
            self.users[followerId].follows.remove(self.users[followeeId])

时间复杂度:O() 空间复杂度:O()

Last updated