355. 设计推特

这里「推特」,可以理解为中国的「微博」、「朋友圈」、「力扣」,真正的数据数需要存在数据库里的,并且还要加上一些非关系型的数据库(redis 等),不能是放在内存里的,这里只是简化了需求。

分析:

这是一类系统设计问题(上周我们做过的 LFU 缓存也是属于这一类问题),通常简化了很多需求,只要题目意思理解清楚,一般情况下不难写出,难在编码的细节和调试;
这里需求 3 和需求 4,只需要维护「我关注的人的 id 列表」 即可,不需要维护「谁关注了我」,由于不需要维护有序性,为了删除和添加方便, 「我关注的人的 id 列表」需要设计成哈希表(HashSet),而每一个人的和对应的他关注的列表存在一个哈希映射(HashMap)里;
最复杂的是需求 2 getNewsFeed(userId):
每一个人的推文和他的 id 的关系,依然是存放在一个哈希表里;
对于每一个人的推文,只有顺序添加的需求,没有查找、修改、删除操作,因此可以使用线性数据结构,链表或者数组均可;
使用数组就需要在尾部添加元素,还需要考虑扩容的问题(使用动态数组);
使用链表就得在头部添加元素,由于链表本身就是动态的,无需考虑扩容;
检索最近的十条推文,需要先把这个用户关注的人的列表拿出来,然后再合并,排序以后选出 Top10,这其实是非常经典的「多路归并」的问题(「力扣」第 23 题:合并K个排序链表),这里需要使用的数据结构是优先队列(就不用去排序了),所以在上一步在存储推文列表的时候使用单链表是合理的,并且应该存储一个时间戳字段,用于比较哪一队的队头元素先出列。
剩下的就是一些细节问题了,例如需要查询关注人(包括自己)的最近十条推文,所以要把自己的推文也放进优先队列里。在出队(优先队列)、入队的时候需要考虑是否为空。

编写对这一类问题,需要仔细调试,并且养成良好的编码习惯,是很不错的编程练习问题。

总结:

如果需要维护数据的时间有序性,链表在特殊场景下可以胜任。因为时间属性通常来说是相对固定的,而不必去维护顺序性;
如果需要动态维护数据有序性,「优先队列」(堆)是可以胜任的,「力扣」上搜索「堆」(heap)标签,可以查看类似的问题;
设计类问题也是一类算法和数据结构的问题,并且做这一类问题有助于我们了解一些数据结构的大致思想和细节,「力扣」上搜索「设计」标签,可以查看类似的问题;
做完这个问题,不妨仔细思考一下这里使用链表存储推文的原因。

image.png
下面是动画演示,可以帮助大家理解「优先队列」是如何在「合并 k 个有序链表」上工作的。只不过「设计推特」这道题不需要去真的合并,并且使用的是最大堆。

这是个「多路归并」的问题,不熟悉的朋友,一定要掌握,非常重要。

题解:

https://leetcode-cn.com/problems/design-twitter/solution/ha-xi-biao-lian-biao-you-xian-dui-lie-java-by-liwe/

大数据排序:https://github.com/chenshuo/recipes/blob/master/topk/word_freq_shards.cc


    // 个人的文章,单项链表,最新的文章为头节点
    struct Tweet {
        int tweetid;
        int timestamp;
        Tweet *next;
        Tweet(int tweet_id, int time_stamp) {
            tweetid = tweet_id;
            timestamp = time_stamp;
            next = nullptr;
        }
    };
    // timestamp越大的,优先级越高
    bool operator > (const Tweet& a, const Tweet& b) {
        return a.timestamp > b.timestamp;
    }
class Twitter {
private:
    // 每个人id和关注人的id
    std::unordered_map<int, set<int>> userid_followerids; // key:userid value:followee userid
    // 每个人的自己的的文章,key:userid, value:tweetid1->tweetid2->nullptr
    std::unordered_map<int, Tweet*> userid_tweeids;
    // 记录时间
    int now_timestamp;
public:
    /** Initialize your data structure here. */
    Twitter() {
        now_timestamp = 0;
    }

    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        // 新的文章
        Tweet* tweet = new Tweet(tweetId, ++now_timestamp);
        // 将文章保存在个人的记录中
        auto ite = userid_tweeids.find(userId);
        if(ite == userid_tweeids.end()) {
            userid_tweeids[userId] = tweet;
        } else {
            // 新文章作为头节点,个人的文章链表是有序的
            tweet->next = ite->second;
            userid_tweeids[userId] = tweet;
        }
    }

    /** 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. */
    vector<int> getNewsFeed(int userId) {
        vector<int> result;
        priority_queue<Tweet*> que;
        auto ite = userid_tweeids.find(userId);
        // 将自己的文章加入
        if(ite != userid_tweeids.end()) {
            que.push(ite->second);
        }
        auto ite2 = userid_followerids.find(userId);
        // 找到关注的人
        if(ite2 != userid_followerids.end()) {
            for(auto ite3 : userid_followerids[userId]) {
                // 看下关注的人是否有文章
                auto ite4 = userid_tweeids.find(ite3);
                if(ite4 != userid_tweeids.end()) {
                    // 将关注人的文章加入
                    que.push(ite4->second);
                }
            }
        }
        int sum = 1;
        while(sum <= 10 && !que.empty()) {
            Tweet* top = que.top();
            result.push_back(top->tweetid);
            que.pop();
            if(top->next != nullptr) {
                que.push(top->next);
            }
            ++sum;
        }
        return std::move(result);
    }

    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        if(followerId == followeeId) {
            return;
        }
        if(userid_followerids.find(followerId) == userid_followerids.end()) {
            userid_followerids[followerId] = std::set<int>{followeeId};
        } else {
            userid_followerids[followerId].insert(followeeId);
        }
    }

    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        if(followerId == followeeId) {
            return;
        }
        if(userid_followerids.find(followerId) != userid_followerids.end()
                && userid_followerids[followerId].find(followeeId) != userid_followerids[followerId].end()) {
            userid_followerids[followerId].erase(followeeId);
        }
    }
};

/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter* obj = new Twitter();
 * obj->postTweet(userId,tweetId);
 * vector<int> param_2 = obj->getNewsFeed(userId);
 * obj->follow(followerId,followeeId);
 * obj->unfollow(followerId,followeeId);
 */

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值