[LeetCode] Design Twitter 设计推特
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:
- postTweet(userId, tweetId): Compose a new tweet.
- getNewsFeed(userId): 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.
- follow(followerId, followeeId): Follower follows a followee.
- unfollow(followerId, followeeId): Follower unfollows a followee.
Example:
Twitter twitter = new Twitter(); // User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5); // User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1); // User 1 follows user 2.
twitter.follow(1, 2); // User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6); // User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1); // User 1 unfollows user 2.
twitter.unfollow(1, 2); // User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);
这道题让我们设计个简单的推特,具有发布消息,获得新鲜事,添加关注和取消关注等功能。我们需要用两个哈希表来做,第一个是建立用户和其所有好友之间的映射,另一个是建立用户和其所有消息之间的映射。由于获得新鲜事是需要按时间顺序排列的,那么我们可以用一个整型变量cnt来模拟时间点,每发一个消息,cnt自增1,那么我们就知道cnt大的是最近发的。那么我们在建立用户和其所有消息之间的映射时,还需要建立每个消息和其时间点cnt之间的映射。这道题的主要难点在于实现getNewsFeed()函数,这个函数获取自己和好友的最近10条消息,我们的做法是用户也添加到自己的好友列表中,然后遍历该用户的所有好友,遍历每个好友的所有消息,维护一个大小为10的哈希表,如果新遍历到的消息比哈希表中最早的消息要晚,那么将这个消息加入,然后删除掉最早的那个消息,这样我们就可以找出最近10条消息了,参见代码如下:
解法一:
class Twitter {
public:
Twitter() {
time = ;
}
void postTweet(int userId, int tweetId) {
follow(userId, userId);
tweets[userId].insert({time++, tweetId});
}
vector<int> getNewsFeed(int userId) {
vector<int> res;
map<int, int> top10;
for (auto id : friends[userId]) {
for (auto a : tweets[id]) {
top10.insert({a.first, a.second});
if (top10.size() > ) top10.erase(top10.begin());
}
}
for (auto a : top10) {
res.insert(res.begin(), a.second);
}
return res;
}
void follow(int followerId, int followeeId) {
friends[followerId].insert(followeeId);
}
void unfollow(int followerId, int followeeId) {
if (followerId != followeeId) {
friends[followerId].erase(followeeId);
}
}
private:
int time;
unordered_map<int, unordered_set<int>> friends;
unordered_map<int, map<int, int>> tweets;
};
下面这种方法和上面的基本一样,就是在保存用户所有消息的时候,用的是vector<pair<int, int>>,这样我们可以用priority_queue来帮助我们找出最新10条消息,参见代码如下:
解法二:
class Twitter {
public:
Twitter() {
time = ;
}
void postTweet(int userId, int tweetId) {
follow(userId, userId);
tweets[userId].push_back({time++, tweetId});
}
vector<int> getNewsFeed(int userId) {
vector<int> res;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
for (auto id : friends[userId]) {
for (auto a : tweets[id]) {
if (q.size() > && q.top().first > a.first && q.size() > ) break;
q.push(a);
if (q.size() > ) q.pop();
}
}
while (!q.empty()) {
res.insert(res.begin(), q.top().second);
q.pop();
}
return res;
}
void follow(int followerId, int followeeId) {
friends[followerId].insert(followeeId);
}
void unfollow(int followerId, int followeeId) {
if (followerId != followeeId) {
friends[followerId].erase(followeeId);
}
}
private:
int time;
unordered_map<int, unordered_set<int>> friends;
unordered_map<int, vector<pair<int, int>>> tweets;
};
参考资料:
https://leetcode.com/problems/design-twitter/
https://leetcode.com/problems/design-twitter/discuss/82849/Short-c%2B%2B-solution
https://leetcode.com/problems/design-twitter/discuss/82916/C%2B%2B-solution-with-max-heap
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Design Twitter 设计推特的更多相关文章
- [LeetCode] 355. Design Twitter 设计推特
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...
- 355 Design Twitter 设计推特
设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文.你的设计需要支持以下的几个功能: postTweet(userI ...
- [leetcode]355. Design Twitter设计实现一个微博系统
//先定义一个数据结构,代表一条微博,有两个内容:发布者id,微博id(代表微博内容) class TwitterData { int userId; int twitterId; public Tw ...
- [LeetCode] Design HashMap 设计HashMap
Design a HashMap without using any built-in hash table libraries. To be specific, your design should ...
- [LeetCode] Design HashSet 设计HashSet
Design a HashSet without using any built-in hash table libraries. To be specific, your design should ...
- [LeetCode] Design Tic-Tac-Toe 设计井字棋游戏
Design a Tic-tac-toe game that is played between two players on a n x n grid. You may assume the fol ...
- [LeetCode] Design TinyURL 设计精简URL地址
Note: For the coding companion problem, please see: Encode and Decode TinyURL. How would you design ...
- LeetCode "Design Twitter"
A mix of hashmap, list and heap. struct Tw { Tw(long long pts, int tid) { ts = pts; tweetid = tid; } ...
- LeetCode 622:设计循环队列 Design Circular Queue
LeetCode 622:设计循环队列 Design Circular Queue 首先来看看队列这种数据结构: 队列:先入先出的数据结构 在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素 ...
随机推荐
- Linux同平台数据库整体物理迁移
Linux同平台数据库整体物理迁移 需求:A机器不再使用,要将A机器的Oracle迁移到B机器. 之前写过类似需求的文章:http://www.cnblogs.com/jyzhao/p/3968504 ...
- CentOS7下安装mysql5.6修改字符集为utf8并开放端口允许远程访问
前言 mysql最初的免费战略已经深入人心,感觉自己一直都在用mysql.今天在centos7下装mysql.发现原来centos下默认没有mysql,因为开始收费了,取而代之的是另一个mysql的分 ...
- HTML光标样式
HTML光标样式 把你的光标放到相应文字上鼠标显示效果 cursor:auto; 自动 cursor:zoom-in; 放大镜 cursor:zoom-out; 缩小镜 curs ...
- 基于 HTML5 的 Web SCADA 报表
背景 最近在一个 SCADA 项目中遇到了在 Web 页面中展示设备报表的需求.一个完整的报表,一般包含了筛选操作区.表格.Chart.展板等多种元素,而其中的数据表格是最常用的控件.在以往的工业项目 ...
- dicom网络通讯入门(2)
第二篇,前面都是闲扯 其实正文现在才开始,这次是把压箱底的东西都拿出来了. 首先我们今天要干的事是实现一个echo响应测试工具 也就是echo 的scu,不是实现打印作业管理么.同学我告诉你还早着呢. ...
- Marshal.Copy将指针拷贝给数组
lpStatuss是一个UNITSTATUS*的指针类型实例,并包含SensorDust字段 //定义一个数组类型 byte[] SensorDust = new byte[30] //将指针类型拷贝 ...
- C#使用Jquery zTree实现树状结构显示_异步数据加载
JQuery-Ztree下载地址:https://github.com/zTree/zTree_v3 JQuery-Ztree数结构演示页面: http://www.treejs.cn/v3/dem ...
- 经典的一款jQuery soChange幻灯片
soChange一款多很经典的幻灯片的jQuery插件. 实例预览 引入文件 <link rel="stylesheet" type="text/css" ...
- 如何解决MSI类型的Sharepoint Server2016 安装即点即用的office 2016 plus问题
前提 在sharepoint server 2016安装office 2016 plus提示如下错误: 解决方法 Ø 概念 1. 即点和即用的概念:即点即用是一种通过 Internet 安装和更新 O ...
- Aircrack-ng: (2) WEP & WPA/WPA2 破解
作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 目录 一. WEP 破解 二. wpa/wpa2 破解 一. WEP 破解 注:步骤前,确保 ...