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); */

相关新闻

情绪救援队长添火乐队《昨日的承诺》的表达入口

情绪救援队长添火乐队《昨日的承诺》的表达入口

从下班路上切入《昨日的承诺》,会比直接说“值得听”更稳,因为听众能马上知道自己该在什么状态下打开它。放在数字音乐和内容传播观察里,这首歌最值得写的是歌名、听感和搜索动作怎样连成一条自然路径。它的价值在于把低处的情绪写得有余温&a…

2026/9/22 13:56:14 阅读更多 →
PyTorch深度学习框架核心技术与实战指南

PyTorch深度学习框架核心技术与实战指南

1. PyTorch框架概述与核心优势PyTorch作为当前最流行的开源深度学习框架之一,已经成为了学术界和工业界的首选工具。我第一次接触PyTorch是在2017年,当时它刚刚发布1.0版本,相比其他框架,最吸引我的是它直观的Pythonic编程风格和动…

2026/9/9 8:52:51 阅读更多 →
10分钟搭建专属3D流程图工具:FossFLOW容器化实战指南

10分钟搭建专属3D流程图工具:FossFLOW容器化实战指南

10分钟搭建专属3D流程图工具:FossFLOW容器化实战指南 【免费下载链接】FossFLOW Make beautiful isometric infrastructure diagrams 项目地址: https://gitcode.com/GitHub_Trending/openflow1/FossFLOW 你是否厌倦了那些复杂难用的流程图工具?想…

2026/9/23 22:24:36 阅读更多 →

最新新闻

Java工业物联网IOT驱动包:统一Modbus-TCP、Bacnet与OPC-UA协议接入

Java工业物联网IOT驱动包:统一Modbus-TCP、Bacnet与OPC-UA协议接入

简介:这份基于Java的物联网IOT通用驱动包设计源码,面向中高级Java开发者与系统集成商,解决Modbus-TCP、Bacnet、OPC-UA等多协议设备接入问题,封装为SDK形式,可直接嵌入业务系统。压缩包共76个文件,约1.73MB…

2026/9/25 3:30:49 阅读更多 →
CRM云端部署与Excel迁移避坑指南

CRM云端部署与Excel迁移避坑指南

1. DeskcommCRM不是“另一个Excel插件”,而是客户数据主权的重建起点你有没有过这样的经历:销售同事发来一份标着“最新客户清单_V12_终版_真的终版.xlsx”的文件,里面混着三张工作表——一张是去年的线索池,一张是今年Q1跟进记录…

2026/9/25 3:30:49 阅读更多 →
RisingWave 开发者文档体系:构建 rustdoc 索引页与核心 crate 导航指南

RisingWave 开发者文档体系:构建 rustdoc 索引页与核心 crate 导航指南

数据库流处理后端数据工程 【免费下载链接】risingwave Event streaming platform for agentic AI. Continuously ingest, transform, and serve event streams in real time, at scale. 项目地址: https://gitcode.com/gh_mirrors/ri/risingwave 点击查看 免费下载…

2026/9/25 3:30:49 阅读更多 →
苹果CMS+油条视频模板视频站搭建全攻略:从宝塔部署到上线备份

苹果CMS+油条视频模板视频站搭建全攻略:从宝塔部署到上线备份

简介:油条视频是一套基于苹果CMS系统的视频建站完整解决方案,面向需要快速搭建影视资源站的站长、运营者及PHP二次开发学习者。系统后台内置自定义参数,可灵活对应会员升级与积分充值页面;视频、演员、专题、收藏、会员等模块齐全…

2026/9/25 3:30:49 阅读更多 →
OpenTTD 编译实战:依赖库、CMake 构建流程与 Windows/多平台调试选项

OpenTTD 编译实战:依赖库、CMake 构建流程与 Windows/多平台调试选项

游戏开发 【免费下载链接】OpenTTD OpenTTD is an open source simulation game based upon Transport Tycoon Deluxe 项目地址: https://gitcode.com/gh_mirrors/op/OpenTTD 点击查看 免费下载 OpenTTD(基于 Transport Tycoon Deluxe 的开源运输模拟游…

2026/9/25 3:30:49 阅读更多 →
robot-dog-swarm-control 使用教程:服务端与客户端如何分工,让多只机器狗听令而同步

robot-dog-swarm-control 使用教程:服务端与客户端如何分工,让多只机器狗听令而同步

robot-dog-swarm-control 使用教程:服务端与客户端如何分工,让多只机器狗听令而同步 【免费下载链接】CupCode_robot-dog-swarm-control模块 源师兄扩展项目: 机器狗群控 | 由源师兄组织创建 项目地址: https://gitcode.com/yuanshixiong/robot-dog-sw…

2026/9/25 3:29:49 阅读更多 →

日新闻

AI元人文:从工具使用到思维重构的深度探索

AI元人文:从工具使用到思维重构的深度探索

最近半年我一直在琢磨一件事:AI元人文到底是什么?说白了,就是“用元视角重新审视人与AI的关系”,也在“探索AI如何反向逼着我们发现自己的思考边界”。标题里的“元探索”,在我看就是一层套一层的追问——当你用AI解决…

2026/9/25 0:00:41 阅读更多 →
Python+CNN车牌识别实战:从数据预处理到模型训练与部署

Python+CNN车牌识别实战:从数据预处理到模型训练与部署

简介:基于Python与卷积神经网络的车牌识别项目,面向计算机视觉初学者及智能交通开发者,目标是帮助用户掌握从数据预处理、模型构建到实际部署的完整流程。压缩包共25个文件,包含jpg/png图像样本、py训练脚本、md说明文档、dat数据…

2026/9/25 0:00:41 阅读更多 →
Vim基础操作全攻略:保存退出、模式切换与高频命令实战

Vim基础操作全攻略:保存退出、模式切换与高频命令实战

1. 项目概述1.1 核心需求解析今天聊聊Vim。写这个题目的原因是:几乎每个后端开发者、运维人员、数据工程师某天都会遇到一个场景——深夜加班,服务器登录界面只有黑底白字,编辑器只有vi/vim,你必须在五分钟内完成一次配置修改并保…

2026/9/25 0:00:41 阅读更多 →

周新闻

Flutter for OpenHarmony游戏卡片渐变背景实战:从原理到性能优化

Flutter for OpenHarmony游戏卡片渐变背景实战:从原理到性能优化

直接铺开项目本身吧。这几个月我一直在折腾一件事:用Flutter给OpenHarmony做一款游戏集合类的App,说白了就是把若干小游戏塞进一个壳里,用统一入口分发。这个方向本身不算新鲜,真正让我花了不少心思的,是首页那堆游戏卡…

2026/9/24 14:34:13 阅读更多 →
Word表格编号全攻略:从列表编号到题注交叉引用

Word表格编号全攻略:从列表编号到题注交叉引用

写Word文档,最让人头疼的往往是那些“看起来不起眼”的小问题。比如表格编号这事:今天在表后面多加了两个空白行,明天给客户交稿前发现整个章节的编号全部错位,光是挨个改序号就能耗掉大半个下午。我前阵子帮人整理一份上百页的技…

2026/9/24 9:10:42 阅读更多 →
从第一个站到第二个站:独立开发者的静态网站选型与落地实践

从第一个站到第二个站:独立开发者的静态网站选型与落地实践

1. 项目概述1.1 核心需求解析做独立开发者这几年,说实话,第一个网站上线的那天晚上我兴奋得没睡着。但等它跑了半年,流量惨淡、功能臃肿、代码自己都懒得看第二遍之后,我才慢慢琢磨明白一个道理:第一个网站是练手&…

2026/9/24 14:33:56 阅读更多 →

月新闻

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能分类:[AI/大模型]细分主题:AI 增强型 CI/CD 流水线自动化与 GitOps 实践:Agent 工作流、工具调用与任务拆解:从原型到生产的验收清单很多团队在尝试用大…

2026/9/24 12:50:34 阅读更多 →
容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场

容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场

容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场分类:[工程技术]细分主题:Kubernetes 生产环境运维与排障实战:可复制的项目复盘模板与决策记录大部分团队的事故复盘报告,最后都变成了躺在 Confluence 或钉…

2026/9/24 14:33:48 阅读更多 →
容器 容器化技术与镜像安全管理:核心链路应该先拆哪一步

容器 容器化技术与镜像安全管理:核心链路应该先拆哪一步

容器 容器化技术与镜像安全管理:核心链路应该先拆哪一步分类:[工程技术]细分主题:Docker 容器化技术与镜像安全管理:核心链路的逐步实现与关键代码取舍面对一个积累了五六年历史包袱的单体架构应用(包含 Web 接口、后台…

2026/9/24 12:49:17 阅读更多 →