Design Twitter解题报告
来源:互联网 发布:淘宝那家零食店好 编辑:程序博客网 时间:2024/04/28 07:10
https://leetcode.com/problems/design-twitter/
这道题是让我们实现一个简单的tweet,就是实现follow用户,unfollow用户和获取最新tweet的功能。最复杂的获取最新tweet。
我们用一个计数器表示时间,每发一条tweet,时间加一,时间越大表示距离现在越近。这里我们维护一个大小为10的map,遍历用户关注的每一个用户发的每一个帖子。
class Twitter {private: int cnt=0; unordered_map<int,set<int>> friends; unordered_map<int,map<int,int>> tweets;public: /** Initialize your data structure here. */ Twitter() { cnt=0; } /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { follow(userId,userId); tweets[userId].insert(pair<int,int>(cnt++,tweetId)); } /** 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) { vector<int> res; map<int,int> top10; for(auto it=friends[userId].begin();it!=friends[userId].end();it++){ int t=*it; for(auto a=tweets[t].begin();a!=tweets[t].end();a++){ if(top10.size()>0&&top10.begin()->first>a->first&&top10.size()>10) break;//这里判断,因为map是排序的,是从小到大排序,如果first比a的都大,说明first比a更近,所以就不用接着比较了。 top10.insert(pair<int,int>(a->first,a->second)); if(top10.size()>10) top10.erase(top10.begin()); } } for (auto it = top10.rbegin(); it != top10.rend(); ++it) { res.push_back(it->second); } return res; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { friends[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){ friends[followerId].erase(followeeId); } }};/** * Your Twitter object will be instantiated and called as such: * Twitter obj = new Twitter(); * obj.postTweet(userId,tweetId); * vector<int> param_2 = obj.getNewsFeed(userId); * obj.follow(followerId,followeeId); * obj.unfollow(followerId,followeeId); */
0 0
- Design Twitter解题报告
- [leetcode] 355. Design Twitter 解题报告
- [Leetcode] 355. Design Twitter 解题报告
- Leetcode 355. Design Twitter 实现一个Twitter系统 解题报告
- leecode 解题总结:355. Design Twitter
- Design Twitter
- Design Twitter
- Design Twitter
- Design Twitter
- Design Twitter
- Design Twitter
- Design Twitter
- USACO Ski Course Design 解题报告
- 【Jason's_ACM_解题报告】Lighting System Design
- 解题报告 之 UVA11400 Lighting System Design
- [leetcode] 362. Design Hit Counter 解题报告
- [leetcode] 353. Design Snake Game 解题报告
- [leetcode] 379. Design Phone Directory 解题报告
- 一个SQL对两个字段排序
- 简析XSS 与 CSRF 两种跨站攻击
- Codeforces Round #332 (Div. 2)A
- Spark-Hive
- hdu 4352 XHXJ's LIS (数位+状态DP)
- Design Twitter解题报告
- [Shell]字符截取命令:cut, printf, awk, sed
- iOS开发中一些重要的系统方法使用注意事项总结
- IntelliJ IDEA,Android Studio使用教程
- IDEA中SpringMvc+Mybatis整合
- UVA 202 Repeating Decimals
- 深度学习(二)大数据智能
- SpannableString的四个flag的用法
- Edit Distance