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 题目汇总

  

最新文章

  1. mongDB-- 3. 查询操作
  2. Mac 使用技巧
  3. 生活life
  4. centos7 docker mysql56
  5. Oracle直方图导致SQL不走索引.
  6. jquery再学习(1)
  7. Hashtable 和 HashMap 的比较
  8. Android打包失败Proguard returned with error code 1. See console
  9. vector容器
  10. 认识和理解css布局中的BFC
  11. JS中childNodes深入学习
  12. luci小记
  13. linux上安装redis的踩坑过程
  14. 使用Spring ThreadPoolTaskExecutor实现多线程任务
  15. zookeeper集群操作【这里只说明简单的操作步骤,zk的相关参数、说明请参考官方文档】
  16. bzoj2830: [Shoi2012]随机树
  17. 基于Centos搭建 Firekylin 个人网站
  18. delphi RTTI 四 获取类属性列表
  19. JavaSE入门学习7:Java基础语法之语句(下)
  20. ASP.NET中常用输出JS脚本的类(来自于周公博客)

热门文章

  1. SignalR入门二、使用 SignalR 2 实现服务器广播
  2. Linux——查询服务器公网IP
  3. Fiddler——手机端无法安装证书
  4. List.Sort
  5. 4-html图片与链接
  6. LeetCode 742. Closest Leaf in a Binary Tree
  7. 洛谷 P1717 钓鱼 题解
  8. Oracle 查看index是否失效
  9. 2019.12.06 java基础
  10. 洛谷 P1948 [USACO08JAN]电话线Telephone Lines 题解