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);

系统设计题,设计一个简单的推特,有发布消息,获得新鲜事,添加关注和取消关注等功能。

参考:linspiration

Java:

public class Twitter {
Map<Integer, Set<Integer>> userMap = new HashMap<>();
Map<Integer, LinkedList<Tweet>> tweets = new HashMap<>();
int timestamp = 0;
class Tweet {
int time;
int id;
Tweet(int time, int id) {
this.time = time;
this.id = id;
}
}
public void postTweet(int userId, int tweetId) {
if (!userMap.containsKey(userId)) userMap.put(userId, new HashSet<>());
userMap.get(userId).add(userId);
if (!tweets.containsKey(userId)) tweets.put(userId, new LinkedList<>());
tweets.get(userId).addFirst(new Tweet(timestamp++, tweetId));
}
public List<Integer> getNewsFeed(int userId) {
if (!userMap.containsKey(userId)) return new LinkedList<>();
PriorityQueue<Tweet> feed = new PriorityQueue<>((t1, t2) -> t2.time-t1.time);
userMap.get(userId).stream().filter(f -> tweets.containsKey(f))
.forEach(f -> tweets.get(f).forEach(feed::add));
List<Integer> res = new LinkedList<>();
while (feed.size() > 0 && res.size() < 10) res.add(feed.poll().id);
return res;
}
public void follow(int followerId, int followeeId) {
if (!userMap.containsKey(followerId)) userMap.put(followerId, new HashSet<>());
userMap.get(followerId).add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
if (userMap.containsKey(followerId) && followeeId != followerId) userMap.get(followerId).remove(followeeId);
}
}  

Python:

class Twitter(object):

    def __init__(self):
"""
Initialize your data structure here.
"""
self.__number_of_most_recent_tweets = 10
self.__followings = collections.defaultdict(set)
self.__messages = collections.defaultdict(list)
self.__time = 0 def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.__time += 1
self.__messages[userId].append((self.__time, tweetId)) def getNewsFeed(self, 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.
:type userId: int
:rtype: List[int]
"""
max_heap = []
if self.__messages[userId]:
heapq.heappush(max_heap, (-self.__messages[userId][-1][0], userId, 0))
for uid in self.__followings[userId]:
if self.__messages[uid]:
heapq.heappush(max_heap, (-self.__messages[uid][-1][0], uid, 0)) result = []
while max_heap and len(result) < self.__number_of_most_recent_tweets:
t, uid, curr = heapq.heappop(max_heap)
nxt = curr + 1;
if nxt != len(self.__messages[uid]):
heapq.heappush(max_heap, (-self.__messages[uid][-(nxt+1)][0], uid, nxt))
result.append(self.__messages[uid][-(curr+1)][1]);
return result def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
if followerId != followeeId:
self.__followings[followerId].add(followeeId) def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.__followings[followerId].discard(followeeId)

C++:

class Twitter {
public:
/** Initialize your data structure here. */
Twitter() : time_(0) { } /** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
messages_[userId].emplace_back(make_pair(++time_, 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) {
using RIT = deque<pair<size_t, int>>::reverse_iterator;
priority_queue<tuple<size_t, RIT, RIT>> heap; if (messages_[userId].size()) {
heap.emplace(make_tuple(messages_[userId].rbegin()->first,
messages_[userId].rbegin(),
messages_[userId].rend()));
}
for (const auto& id : followings_[userId]) {
if (messages_[id].size()) {
heap.emplace(make_tuple(messages_[id].rbegin()->first,
messages_[id].rbegin(),
messages_[id].rend()));
}
}
vector<int> res;
while (!heap.empty() && res.size() < number_of_most_recent_tweets_) {
const auto& top = heap.top();
size_t t;
RIT begin, end;
tie(t, begin, end) = top;
heap.pop(); auto next = begin + 1;
if (next != end) {
heap.emplace(make_tuple(next->first, next, end));
} res.emplace_back(begin->second);
}
return res;
} /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
if (followerId != followeeId && !followings_[followerId].count(followeeId)) {
followings_[followerId].emplace(followeeId);
}
} /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
if (followings_[followerId].count(followeeId)) {
followings_[followerId].erase(followeeId);
}
} private:
const size_t number_of_most_recent_tweets_ = 10;
unordered_map<int, unordered_set<int>> followings_;
unordered_map<int, deque<pair<size_t, int>>> messages_;
size_t time_;
};

  

All LeetCode Questions List 题目汇总

  

[LeetCode] 355. Design Twitter 设计推特的更多相关文章

  1. 355 Design Twitter 设计推特

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

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

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

  3. [LeetCode] Design Twitter 设计推特

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

  4. leetcode@ [355] Design Twitter (Object Oriented Programming)

    https://leetcode.com/problems/design-twitter/ Design a simplified version of Twitter where users can ...

  5. 【LeetCode】355. Design Twitter 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  6. 【Leetcode】355. Design Twitter

    题目描述: Design a simplified version of Twitter where users can post tweets, follow/unfollow another us ...

  7. 355. Design Twitter

    二刷尝试了别的办法,用MAP代表关注列表. 然后不初始化,但是只要有用户被使用,而他又不在MAP里,就把他加进去,然后让他关注自己.. 但是这样做超时了. 问题在于这个题解法太多,有很多不同的情况. ...

  8. leetcode 355 Design Twitte

    题目连接 https://leetcode.com/problems/design-twitter Design Twitte Description Design a simplified vers ...

  9. [LeetCode] 534. Design TinyURL 设计短网址

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

随机推荐

  1. BLE——协议层次结构

    未完待续…… BLE协议 Bluetooth Application Applications GATT-Based Profiles/Services Bluetooth Core (Stack) ...

  2. D. Zero Quantity Maximization ( Codeforces Round #544 (Div. 3) )

    题目链接 参考题解 题意: 给你 整形数组a 和 整形数组b ,要你c[i] = d * a[i] + b[i], 求  在c[i]=0的时候  相同的d的数量 最多能有几个. 思路: 1. 首先打开 ...

  3. Java7与Java8中的HashMap和ConcurrentHashMap知识点总结

    JAVA7 Java7的ConcurrentHashMap里有多把锁,每一把锁用于其中一部分数据,那么当多线程访问容器里不同数据段的数据时,线程间就不会存在锁竞争,从而可以有效的提高并发访问效率呢.这 ...

  4. 一加5安卓P刷入twrp的recovery

    本文介绍的方法属于普适性的一般方法,比网上的各种工具箱会繁琐.但是工具箱不一定一直会更新(之前一加论坛的刷机工具箱已经停止更新了,估计是作者不用一加5了吧,毕竟已经好几年的手机了).并且如果你手机更新 ...

  5. danci5

    foss community 自由软体社区 可理解为开源 program 英 ['prəʊɡræm] 美 ['proɡræm] n. 程序:计划:大纲 vt. 用程序指令:为…制订计划:为…安排节目 ...

  6. git create remote branch (五)

    admin@PC-panzidong MINGW64 ~/WebstormProjects/backEndServer (master) 查看本地分支信息$ git branch* master ad ...

  7. WinDbg常用命令系列---!address

    !address 这个!address扩展命令显示有关目标进程或目标计算机使用的内存的信息. 用户模式: !address Address !address -summary !address [-f ...

  8. 学生管理系统(Nodejs)

    一.项目介绍 ①使用nodejs+bootstrap开发 ②对文件进行合理的模块化 ③实现基本的增删改查功能 二.思路 ①处理模块,处理模块,配置开发静态资源,配置模块引擎 ②路由设计,提取路由模块 ...

  9. C++2.0新特性(六)——<Smart Pointer(智能指针)之shared_ptr>

    Smart Pointer(智能指针)指的是一类指针,并不是单一某一个指针,它能知道自己被引用的个数以至于在最后一个引用消失时销毁它指向的对象,本文主要介绍C++2.0提供的新东西 一.Smart P ...

  10. 软件工程 “校园汇” 个人IDEA竞选分析与总结

    IDEA竞选 19/10/8软件工程课上举行了一次IDEA竞选: 我的竞选IDEA是"校友汇",大学生的在线活动中心. 投票结果: 可以看到,校友会(汇)IDEA竞选结果十分惨淡, ...