当前位置: 首页 > news >正文

C++ | Leetcode C++题解之第355题设计推特

题目:

题解:

class Twitter {struct Node {// 哈希表存储关注人的 Idunordered_set<int> followee;// 用链表存储 tweetIdlist<int> tweet;};// getNewsFeed 检索的推文的上限以及 tweetId 的时间戳int recentMax, time;// tweetId 对应发送的时间unordered_map<int, int> tweetTime;// 每个用户存储的信息unordered_map<int, Node> user;
public:Twitter() {time = 0;recentMax = 10;user.clear();}// 初始化void init(int userId) {user[userId].followee.clear();user[userId].tweet.clear();}void postTweet(int userId, int tweetId) {if (user.find(userId) == user.end()) {init(userId);}// 达到限制,剔除链表末尾元素if (user[userId].tweet.size() == recentMax) {user[userId].tweet.pop_back();}user[userId].tweet.push_front(tweetId);tweetTime[tweetId] = ++time;}vector<int> getNewsFeed(int userId) {vector<int> ans; ans.clear();for (list<int>::iterator it = user[userId].tweet.begin(); it != user[userId].tweet.end(); ++it) {ans.emplace_back(*it);}for (int followeeId: user[userId].followee) {if (followeeId == userId) continue; // 可能出现自己关注自己的情况vector<int> res; res.clear();list<int>::iterator it = user[followeeId].tweet.begin();int i = 0;// 线性归并while (i < (int)ans.size() && it != user[followeeId].tweet.end()) {if (tweetTime[(*it)] > tweetTime[ans[i]]) {res.emplace_back(*it);++it;} else {res.emplace_back(ans[i]);++i;}// 已经找到这两个链表合起来后最近的 recentMax 条推文if ((int)res.size() == recentMax) break;}for (; i < (int)ans.size() && (int)res.size() < recentMax; ++i) res.emplace_back(ans[i]);for (; it != user[followeeId].tweet.end() && (int)res.size() < recentMax; ++it) res.emplace_back(*it);ans.assign(res.begin(),res.end());}return ans;}void follow(int followerId, int followeeId) {if (user.find(followerId) == user.end()) {init(followerId);}if (user.find(followeeId) == user.end()) {init(followeeId);}user[followerId].followee.insert(followeeId);}void unfollow(int followerId, int followeeId) {user[followerId].followee.erase(followeeId);}
};
http://www.lryc.cn/news/431183.html

相关文章:

  • 构建并训练卷积神经网络(CNN)对CIFAR-10数据集进行分类
  • flowable 根据xml 字符串生成流程图
  • AI建模——AI生成3D内容算法产品介绍与模型免费下载
  • 在Go中迅速使用RabbitMQ
  • Windows JDK安装详细教程
  • Ribbon负载均衡底层原理
  • 【C语言可变参数函数的使用与原理分析】
  • 【笔记】Java EE应用开发环境配置(JDK+Maven+Tomcat+MySQL+IDEA)
  • 一文讲懂扩散模型
  • 学习笔记八:基于Jenkins+k8s+Git+DockerHub等技术链构建企业级DevOps容器云平台
  • 科研绘图系列:R语言柱状图分布(histogram plot)
  • vue3+ts封装类似于微信消息的组件
  • ES6 reduce方法详解:示例、应用场景与实用技巧
  • java后端保存的本地图片通过ip+端口直接访问
  • 2024 年高教社杯全国大学生数学建模竞赛B题4小问解题思路(第二版)
  • docker-nginx数据卷挂载
  • 项目实战 ---- 商用落地视频搜索系统(8)---优化(2)---查询逻辑层优化
  • 山东大学机试试题合集
  • 餐厅食品留样管理系统小程序的设计
  • 亚马逊运营:如何提高亚马逊销量和运营效率?
  • 设计模式背后的设计原则和思想
  • 项目总体框架
  • k8s Prometheus
  • glsl着色器学习(九)屏幕像素空间和设置颜色
  • 前端框架有哪些?
  • 分类预测|基于黑翅鸢优化轻量级梯度提升机算法数据预测Matlab程序BKA-LightGBM多特征输入多类别输出 含对比
  • 利用大模型实时提取和检索多模态数据探索-利用 Indexify 进行文档分析
  • 函数式接口实现策略模式
  • 鸿蒙Next-拉起支付宝的三种方式——教程
  • Vue.js 组件化开发:父子组件通信与组件注册详解