150强访谈简单

设计推特

“设计 Twitter”问题的详细指南和 Python 实现。

问题陈述

简单

设计 Twitter 的简化版本,用户可以在其中发布推文、关注/取消关注其他用户,并且能够在用户的新闻源中查看最新的 10 条推文。

实现 Twitter 类:

- Twitter() 初始化您的 Twitter 对象。

- postTweet(userId: int, tweetId: int) 由用户 userId 撰写一条 ID 为 tweetId 的新推文。

- getNewsFeed(userId: int) -> List[int] 检索用户新闻源中最新的 10 条推文 ID。

- follow(followerId: int, followeeId: int) ID 为 followerId 的用户开始关注 ID 为 followeeId 的用户。

- unfollow(followerId: int, followeeId: int) ID 为 followerId 的用户开始取消关注 ID 为 followeeId 的用户。

输入是操作和参数的列表。实现一个返回结果列表的函数 twitter(operations: list, arguments: list) -> list (对于构造函数/postTweet/follow/unfollow 为 None,对于 getNewsFeed 为 List[int])。

约束条件
  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10^4
  • All the tweets have unique IDs
  • At most 30000 calls will be made in total

示例

Example 1
Input
operations = ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"], arguments = [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[None, None, [5], None, None, [6, 5], None, [5]]
Explanation

User 1 posts tweet 5. News feed: [5]. User 1 follows 2. User 2 posts tweet 6. News feed: [6, 5]. User 1 unfollows 2. News feed: [5].

Need a Hint?
考虑使用堆/优先级队列特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。