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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。