# leetcode-design-twitter

2020年4月14日

### 355. 设计推特

题目

做出来倒是很简单，由于没有并发和特别的条件，测试数据量也不大。一开始搞错了，以为传入的 `twitterId` 就是自增的 id，结果其实是每条推的内容，所以增加了一个计数器去标记 id。

主要的考点应该是 `多路归并` 这个东西。我用的是排序，在数据量大的时候应该会有些问题。

    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
    52
    53
    54
    55
    56
    57
    58
    59

    class Twitter:

      def __init__(self):
        """
        Initialize your data structure here.
        """
        self.tweets = {}
        self.followers = {}
        self._tid = 0

      def postTweet(self, userId: int, tweetId: int) -> None:
        """
        Compose a new tweet.
        """
        if not self.tweets.get(userId):
          self.tweets[userId] = []
        self.tweets[userId].append((self._tid, tweetId))
        self._tid += 1

      def getNewsFeed(self, userId: int) :
        """
        Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
        """
        foers = self.followers.get(userId, set())
        foers = foers.union((userId,))
        tweets = []
        for fo in foers:
          tweets.extend(self.tweets.get(fo, [])[-10:])
        return [tw[1] for tw in sorted(tweets, reverse=True)[:10]]

      def follow(self, followerId: int, followeeId: int) -> None:
        """
        Follower follows a followee. If the operation is invalid, it should be a no-op.
        """
        if not self.followers.get(followerId):
          self.followers[followerId] = set()
        self.followers[followerId].add(followeeId)

      def unfollow(self, followerId: int, followeeId: int) -> None:
        """
        Follower unfollows a followee. If the operation is invalid, it should be a no-op.
        """
        if not self.followers.get(followerId):
          self.followers[followerId] = set()
        if followeeId in self.followers[followerId]:
          self.followers[followerId].remove(followeeId)

    #100 ms	19.2 MB

    # Your Twitter object will be instantiated and called as such:
    # obj = Twitter()
    # obj.postTweet(userId,tweetId)
    # param_2 = obj.getNewsFeed(userId)
    # obj.follow(followerId,followeeId)
    # obj.unfollow(followerId,followeeId)