公司动态
355. 设计推特(系统设计)
这里「推特」可以理解为中国的「微博」、「朋友圈」、「力扣」真正的数据数需要存在数据库里的并且还要加上一些非关系型的数据库redis 等不能是放在内存里的这里只是简化了需求。分析这是一类系统设计问题上周我们做过的 LFU 缓存也是属于这一类问题通常简化了很多需求只要题目意思理解清楚一般情况下不难写出难在编码的细节和调试这里需求 3 和需求 4只需要维护「我关注的人的 id 列表」 即可不需要维护「谁关注了我」由于不需要维护有序性为了删除和添加方便 「我关注的人的 id 列表」需要设计成哈希表HashSet而每一个人的和对应的他关注的列表存在一个哈希映射HashMap里最复杂的是需求 2 getNewsFeed(userId):每一个人的推文和他的 id 的关系依然是存放在一个哈希表里对于每一个人的推文只有顺序添加的需求没有查找、修改、删除操作因此可以使用线性数据结构链表或者数组均可使用数组就需要在尾部添加元素还需要考虑扩容的问题使用动态数组使用链表就得在头部添加元素由于链表本身就是动态的无需考虑扩容检索最近的十条推文需要先把这个用户关注的人的列表拿出来然后再合并排序以后选出 Top10这其实是非常经典的「多路归并」的问题「力扣」第 23 题合并K个排序链表这里需要使用的数据结构是优先队列就不用去排序了所以在上一步在存储推文列表的时候使用单链表是合理的并且应该存储一个时间戳字段用于比较哪一队的队头元素先出列。剩下的就是一些细节问题了例如需要查询关注人包括自己的最近十条推文所以要把自己的推文也放进优先队列里。在出队优先队列、入队的时候需要考虑是否为空。编写对这一类问题需要仔细调试并且养成良好的编码习惯是很不错的编程练习问题。总结如果需要维护数据的时间有序性链表在特殊场景下可以胜任。因为时间属性通常来说是相对固定的而不必去维护顺序性如果需要动态维护数据有序性「优先队列」堆是可以胜任的「力扣」上搜索「堆」heap标签可以查看类似的问题设计类问题也是一类算法和数据结构的问题并且做这一类问题有助于我们了解一些数据结构的大致思想和细节「力扣」上搜索「设计」标签可以查看类似的问题做完这个问题不妨仔细思考一下这里使用链表存储推文的原因。下面是动画演示可以帮助大家理解「优先队列」是如何在「合并 k 个有序链表」上工作的。只不过「设计推特」这道题不需要去真的合并并且使用的是最大堆。这是个「多路归并」的问题不熟悉的朋友一定要掌握非常重要。题解355. 设计推特 - 力扣LeetCode大数据排序recipes/topk/word_freq_shards.cc at master · chenshuo/recipes · GitHub// 个人的文章单项链表最新的文章为头节点 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_mapint, setint userid_followerids; // key:userid value:followee userid // 每个人的自己的的文章,key:userid, value:tweetid1-tweetid2-nullptr std::unordered_mapint, 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 users 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. */ vectorint getNewsFeed(int userId) { vectorint result; priority_queueTweet* 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::setint{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); * vectorint param_2 obj-getNewsFeed(userId); * obj-follow(followerId,followeeId); * obj-unfollow(followerId,followeeId); */写扩散class Twitter { private: struct Tweet { int tweetId; int userId; int time; }; int timestamp; // 用户自己的推文列表用于历史导入 unordered_mapint, vectorTweet userTweets; // 关注关系followerId - set of followeeId unordered_mapint, unordered_setint followees; // 粉丝关系followeeId - set of followerId (用于发推时推送) unordered_mapint, unordered_setint fans; // 每个用户的收件箱按时间升序 unordered_mapint, listTweet timeline; public: Twitter() : timestamp(0) {} void postTweet(int userId, int tweetId) { Tweet t{ tweetId, userId, timestamp }; userTweets[userId].push_back(t); // 推送给所有粉丝 for (int fan : fans[userId]) { timeline[fan].push_back(t); } // 自己也有一份 timeline[userId].push_back(t); } vectorint getNewsFeed(int userId) { vectorint res; auto list timeline[userId]; auto it list.end(); int cnt 0; while (it ! list.begin() cnt 10) { --it; res.push_back(it-tweetId); cnt; } return res; } void follow(int followerId, int followeeId) { if (followerId followeeId) return; if (followees[followerId].count(followeeId)) return; // 已关注 followees[followerId].insert(followeeId); fans[followeeId].insert(followerId); // 将 followee 的历史推文导入 follower 的 timeline按时间升序 auto tweets userTweets[followeeId]; auto tl timeline[followerId]; auto it tl.begin(); for (const auto t : tweets) { while (it ! tl.end() it-time t.time) it; tl.insert(it, t); } } void unfollow(int followerId, int followeeId) { if (!followees[followerId].count(followeeId)) return; followees[followerId].erase(followeeId); fans[followeeId].erase(followerId); // 从 follower 的 timeline 中删除所有来自 followee 的推文 auto tl timeline[followerId]; for (auto it tl.begin(); it ! tl.end(); ) { if (it-userId followeeId) { it tl.erase(it); } else { it; } } } };读扩散class Twitter { private: struct Node { int tweetId; int time_id; Node(int id1, int id2) { tweetId id1; time_id id2; } }; public: Twitter() { _time_id 0; } void postTweet(int userId, int tweetId) { _table[userId].push_front(Node(tweetId, _time_id)); _time_id; } struct PNode { bool operator(const PNode node) const { return ite-time_id node.ite-time_id; } int user_id; std::listNode::iterator ite; }; vectorint getNewsFeed(int userId) { unordered_setint followers _followers[userId]; followers.insert(userId); priority_queuePNode que; for (auto f : followers) { cout f: f endl; if (_table[f].empty()) { continue; } PNode n; n.user_id f; n.ite _table[f].begin(); que.push(n); } vectorint result; while (!que.empty() result.size() 10) { auto f que.top(); que.pop(); result.push_back(f.ite-tweetId); f.ite; if (f.ite ! _table[f.user_id].end()) { que.push(f); } } return result; } void follow(int followerId, int followeeId) { _followers[followerId].insert(followeeId); } void unfollow(int followerId, int followeeId) { _followers[followerId].erase(followeeId); } private: private: int _time_id; unordered_mapint, listNode _table; unordered_mapint, unordered_setint _followers; }; /** * Your Twitter object will be instantiated and called as such: * Twitter* obj new Twitter(); * obj-postTweet(userId,tweetId); * vectorint param_2 obj-getNewsFeed(userId); * obj-follow(followerId,followeeId); * obj-unfollow(followerId,followeeId); */