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:

  1. postTweet(userId, tweetId): Compose a new tweet.
  2. 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.
  3. follow(followerId, followeeId): Follower follows a followee.
  4. 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 设计推特的更多相关文章

  1. [LeetCode] 355. Design Twitter 设计推特

    Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...

  2. 355 Design Twitter 设计推特

    设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文.你的设计需要支持以下的几个功能:    postTweet(userI ...

  3. [leetcode]355. Design Twitter设计实现一个微博系统

    //先定义一个数据结构,代表一条微博,有两个内容:发布者id,微博id(代表微博内容) class TwitterData { int userId; int twitterId; public Tw ...

  4. [LeetCode] Design HashMap 设计HashMap

    Design a HashMap without using any built-in hash table libraries. To be specific, your design should ...

  5. [LeetCode] Design HashSet 设计HashSet

    Design a HashSet without using any built-in hash table libraries. To be specific, your design should ...

  6. [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 ...

  7. [LeetCode] Design TinyURL 设计精简URL地址

    Note: For the coding companion problem, please see: Encode and Decode TinyURL. How would you design ...

  8. LeetCode "Design Twitter"

    A mix of hashmap, list and heap. struct Tw { Tw(long long pts, int tid) { ts = pts; tweetid = tid; } ...

  9. LeetCode 622:设计循环队列 Design Circular Queue

    LeetCode 622:设计循环队列 Design Circular Queue 首先来看看队列这种数据结构: 队列:先入先出的数据结构 在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素 ...

随机推荐

  1. vertical-align浅析

    一直以来都搞不懂vertical-align,它适用于什么元素,它的对齐规则是什么样的.索性查了下w3c相关规范,发现行高和基线对齐的规范说明里有如下内容: This section is being ...

  2. Android来电监听和去电监听

    我觉得写文章就得写得有用一些的,必须要有自己的思想,关于来电去电监听将按照下面三个问题展开 1.监听来电去电有什么用? 2.怎么监听,来电去电监听方式一样吗? 3.实战,有什么需要特别注意地方? 监听 ...

  3. Java DNS查询内部实现

    源码分析 在Java中,DNS相关的操作都是通过通过InetAddress提供的API实现的.比如查询域名对应的IP地址: String dottedQuadIpAddress = InetAddre ...

  4. js数组去重

    这就是数组去重了...var str=['hello','node','element','node','hello','blue','red'];var str1=[]; function firs ...

  5. .Net语言 APP开发平台——Smobiler学习日志:快速实现手机上的图片上传功能

    最前面的话:Smobiler是一个在VS环境中使用.Net语言来开发APP的开发平台,也许比Xamarin更方便 一.目标样式 我们要实现上图中的效果,需要如下的操作: 1.从工具栏上的"S ...

  6. 异步编程系列第01章 Async异步编程简介

    p { display: block; margin: 3px 0 0 0; } --> 2016.10.11补充 三个月过去了,回头来看,我不得不承认这是一系列失败的翻译.过段时间,我将重新翻 ...

  7. C#开发微信门户及应用(10)--在管理系统中同步微信用户分组信息

    在前面几篇文章中,逐步从原有微信的API封装的基础上过渡到微信应用平台管理系统里面,逐步介绍管理系统中的微信数据的界面设计,以及相关的处理操作过程的逻辑和代码,希望从更高一个层次,向大家介绍微信的应用 ...

  8. python推荐淘宝物美价廉商品

    完成的目标: 输入搜索的商品 以及 淘宝的已评价数目.店铺的商品描述(包括如实描述.服务态度.快递的5.0打分): 按要求,晒选出要求数量的结果,并按"物美价廉算法"排序后输出 思 ...

  9. Maven对插件进行全局设置

    并不是所有插件都适合从命令行配置,有些参数的值从项目创建到发布都不会改变,或者很少改变,对于这种情况,在POM文件中一次性配置就显然比重复在命令行中输入要方便了. 用户可以在生命插件的时候,对插件进行 ...

  10. quartz CronExpression表达式

    一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素.按顺序依次为1.秒(0~59)2.分钟(0~59)3.小时(0~23)4.天(月)(0~31,但是你需要考虑你月的天数)5.月(0~11 ...