设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文。你的设计需要支持以下的几个功能: 来源:力扣(LeetCode) 532 ms 21.7 MB
1. 题目
postTweet(userId, tweetId)
: 创建一条新的推文getNewsFeed(userId)
: 检索最近的十条推文。每个推文都必须是由此用户关注的人或者是用户自己发出的。推文必须按照时间顺序由最近的开始排序。follow(followerId, followeeId)
: 关注一个用户unfollow(followerId, followeeId)
: 取消关注一个用户示例: Twitter twitter = new Twitter(); // 用户1发送了一条新推文 (用户id = 1, 推文id = 5). twitter.postTweet(1, 5); // 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文. twitter.getNewsFeed(1); // 用户1关注了用户2. twitter.follow(1, 2); // 用户2发送了一个新推文 (推文id = 6). twitter.postTweet(2, 6); // 用户1的获取推文应当返回一个列表,其中包含两个推文,id分别为 -> [6, 5]. // 推文id6应当在推文id5之前,因为它是在5之后发送的. twitter.getNewsFeed(1); // 用户1取消关注了用户2. twitter.unfollow(1, 2); // 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文. // 因为用户1已经不再关注用户2. twitter.getNewsFeed(1);
链接:https://leetcode-cn.com/problems/design-twitter
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。2. 解题
struct cmp { bool operator()(const vector<int> &a, const vector<int> &b) const { return a[0] < b[0]; } }; class Twitter { unordered_map<int,unordered_set<int>> m;//id,关注的人 set<vector<int>,cmp> tweet;//time, 推文id,用户id int time = 0; int count; vector<int> ans; public: /** Initialize your data structure here. */ Twitter() {} /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { tweet.insert({time++, tweetId, 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. */ vector<int> getNewsFeed(int userId) { count = 10; ans.clear(); for(auto it = tweet.rbegin(); it != tweet.rend() && count; ++it) { if((*it)[2]==userId || m[userId].count((*it)[2])) { ans.push_back((*it)[1]); count--; } } return ans; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { m[followerId].insert(followeeId); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ void unfollow(int followerId, int followeeId) { m[followerId].erase(followeeId); } };
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算