设计推特

标签: 设计 哈希表 链表 堆(优先队列)

难度: Medium

设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近 10 条推文。

实现 Twitter 类:

  • Twitter() 初始化简易版推特对象
  • void postTweet(int userId, int tweetId) 根据给定的 tweetIduserId 创建一条新推文。每次调用此函数都会使用一个不同的 tweetId
  • List<Integer> getNewsFeed(int userId) 检索当前用户新闻推送中最近  10 条推文的 ID 。新闻推送中的每一项都必须是由用户关注的人或者是用户自己发布的推文。推文必须 按照时间顺序由最近到最远排序
  • void follow(int followerId, int followeeId) ID 为 followerId 的用户开始关注 ID 为 followeeId 的用户。
  • void unfollow(int followerId, int followeeId) ID 为 followerId 的用户不再关注 ID 为 followeeId 的用户。

示例:

输入
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
输出
[null, null, [5], null, null, [6, 5], null, [5]]

解释
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // 用户 1 发送了一条新推文 (用户 id = 1, 推文 id = 5)
twitter.getNewsFeed(1);  // 用户 1 的获取推文应当返回一个列表,其中包含一个 id 为 5 的推文
twitter.follow(1, 2);    // 用户 1 关注了用户 2
twitter.postTweet(2, 6); // 用户 2 发送了一个新推文 (推文 id = 6)
twitter.getNewsFeed(1);  // 用户 1 的获取推文应当返回一个列表,其中包含两个推文,id 分别为 -> [6, 5] 。推文 id 6 应当在推文 id 5 之前,因为它是在 5 之后发送的
twitter.unfollow(1, 2);  // 用户 1 取消关注了用户 2
twitter.getNewsFeed(1);  // 用户 1 获取推文应当返回一个列表,其中包含一个 id 为 5 的推文。因为用户 1 已经不再关注用户 2

提示:

  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 104
  • 所有推特的 ID 都互不相同
  • postTweetgetNewsFeedfollowunfollow 方法最多调用 3 * 104

Submission

运行时间: 32 ms

内存: 14.9 MB

import time
import heapq
from collections import defaultdict


class Tweet:

    def __init__(self, _id, ts, _next=None):
        self.id = _id
        self.ts = ts
        self.next = _next


class Twitter:

    def __init__(self):
        """
        Initialize your data structure here.--
        """
        self.follow_relation = defaultdict(set)
        self.user_tweets = dict()

    def postTweet(self, userId: int, tweetId: int) -> None:
        """
        Compose a new tweet.
        """
        head = self.user_tweets.get(userId)
        if head is None:
            new_head = Tweet(tweetId, time.time_ns())
        else:
            new_head = Tweet(tweetId, time.time_ns(), _next=head)
        self.user_tweets[userId] = new_head

    def getNewsFeed(self, userId: int) -> List[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.
        """
        h = []
        for followeeId in self.follow_relation[userId]:
            if followeeId in self.user_tweets:
                head = self.user_tweets[followeeId]
                heapq.heappush(h, (-head.ts, head))

        if userId in self.user_tweets:
            head = self.user_tweets[userId]
            heapq.heappush(h, (-head.ts, head))

        ret = []
        while h:
            _, tweet = heapq.heappop(h)
            ret.append(tweet.id)
            if len(ret) == 10:
                return ret
            if tweet.next:
                heapq.heappush(h, (-tweet.next.ts, tweet.next))
        return ret

    def follow(self, followerId: int, followeeId: int) -> None:
        """
        Follower follows a followee. If the operation is invalid, it should be a no-op.
        """
        if followeeId == followerId:
            return

        self.follow_relation[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.
        """
        self.follow_relation[followerId].discard(followeeId)


# 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)

Explain

该题解使用了哈希表和堆来实现一个简化版的推特系统。具体思路如下: 1. 用户与关注者的关系使用哈希表 follow_relation 存储,其中 key 为用户 ID,value 为该用户关注的用户 ID 集合。 2. 用户发布的推文使用哈希表 user_tweets 存储,其中 key 为用户 ID,value 为该用户发布的推文链表的头节点。 3. 发布推文时,创建一个新的推文节点,将其插入到对应用户的推文链表头部。 4. 获取用户的新闻推送时,遍历该用户关注的所有用户(包括自己),将他们的最新推文加入到一个最大堆中,堆的排序依据为推文的时间戳。 5. 从最大堆中依次取出最多 10 条最新的推文 ID,存入结果列表并返回。 6. 关注/取消关注操作通过修改 follow_relation 哈希表实现。

时间复杂度: postTweet: O(1) getNewsFeed: O(NlogM),其中 N 为关注人数,M 为推文总数 follow: O(1) unfollow: O(1)

空间复杂度: O(F+T),其中 F 为关注关系总数,T 为推文总数

import time
import heapq
from collections import defaultdict


class Tweet:

    def __init__(self, _id, ts, _next=None):
        self.id = _id
        self.ts = ts
        self.next = _next


class Twitter:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.follow_relation = defaultdict(set)  # 用户关注关系哈希表
        self.user_tweets = dict()  # 用户推文哈希表

    def postTweet(self, userId: int, tweetId: int) -> None:
        """
        Compose a new tweet.
        """
        head = self.user_tweets.get(userId)
        if head is None:
            new_head = Tweet(tweetId, time.time_ns())  # 创建新推文节点
        else:
            new_head = Tweet(tweetId, time.time_ns(), _next=head)  # 创建新推文节点并将其插入链表头部
        self.user_tweets[userId] = new_head  # 更新用户推文哈希表

    def getNewsFeed(self, userId: int) -> List[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.
        """
        h = []
        for followeeId in self.follow_relation[userId]:  # 遍历关注的用户
            if followeeId in self.user_tweets:
                head = self.user_tweets[followeeId]
                heapq.heappush(h, (-head.ts, head))  # 将关注用户的最新推文加入堆

        if userId in self.user_tweets:  # 将自己的最新推文也加入堆
            head = self.user_tweets[userId]
            heapq.heappush(h, (-head.ts, head))

        ret = []
        while h:
            _, tweet = heapq.heappop(h)  # 从堆中取出时间戳最大的推文
            ret.append(tweet.id)
            if len(ret) == 10:  # 最多返回 10 条推文
                return ret
            if tweet.next:  # 将下一条推文加入堆
                heapq.heappush(h, (-tweet.next.ts, tweet.next))
        return ret

    def follow(self, followerId: int, followeeId: int) -> None:
        """
        Follower follows a followee. If the operation is invalid, it should be a no-op.
        """
        if followeeId == followerId:
            return

        self.follow_relation[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.
        """
        self.follow_relation[followerId].discard(followeeId)  # 更新关注关系哈希表


# 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)

Explore

链表在存储用户推文时被选用主要是因为其在插入操作中具有高效的性能。每当用户发布新推文时,可以直接将新推文节点插入到链表的头部,这个操作的时间复杂度为O(1),非常快速。相比之下,如果使用数组,每次添加新元素可能需要移动其他所有元素或进行动态扩容,这在时间复杂度上通常是O(n)或者平均O(1)但最坏情况下是O(n)。虽然栈也可以实现O(1)的插入时间复杂度,但链表更加灵活,尤其是在涉及到元素的删除或在链表中间添加元素时更加高效。

堆中的元素数量最多等于用户关注的人数加上用户自己,因为堆中最初只存储每个用户的最新一条推文。如果用户关注的人数非常多,堆的大小确实会增加,这可能会影响性能,尤其是堆操作(如插入和删除)的时间复杂度为O(log n)。不过,考虑到通常一个用户关注的人数不会极端庞大,这种设计在大多数情况下是可行的。

为了优化这种情况下的性能,可以考虑使用更复杂的数据结构,比如延迟加载机制。例如,不是一开始就加载所有推文到堆中,而是每次从堆中取出一条推文后,再加载该用户的下一条推文到堆中。这样可以减少堆中同时存在的元素数量,从而优化相关的堆操作。此外,还可以考虑使用缓存策略,缓存用户经常访问的信息,减少每次都需要完全重建堆的情况。

在用户取消关注某人后,该操作不会影响已经生成的新闻推送列表,因为这些列表是根据当时的关注关系生成的。如果用户在取消关注后再次请求新闻推送,系统将不会包括已取消关注用户的推文,因为新的推送列表是基于当前有效的关注关系重新生成的。这样确保了新闻推送的实时性和个性化。