動機
原本以為很複雜,結果異常的簡單
Problem
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.
Implement the Twitter
class:
- t
Twitter()
Initializes your twitter object. tvoid postTweet(int userId, int tweetId)
Composes a new tweet with IDtweetId
by the useruserId
. Each call to this function will be made with a uniquetweetId
. tList
Retrieves thegetNewsFeed(int userId) 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 themself. Tweets must be ordered from most recent to least recent. tvoid follow(int followerId, int followeeId)
The user with IDfollowerId
started following the user with IDfolloweeId
. tvoid unfollow(int followerId, int followeeId)
The user with IDfollowerId
started unfollowing the user with IDfolloweeId
.
Example 1:
Input["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"][[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]Output[Algorithm, Leetcode, null, [5], null, null, [6, 5], null, [5]]ExplanationTwitter twitter = new Twitter();twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]twitter.follow(1, 2); // User 1 follows user 2.twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).twitter.getNewsFeed(1); // 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.unfollow(1, 2); // User 1 unfollows user 2.twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
Constraints:
- t
1 <= userId, followerId, followeeId <= 500
t0 <= tweetId <= 104
t- All the tweets have unique IDs. t
- At most
3 * 104
calls will be made topostTweet
,getNewsFeed
,follow
, andunfollow
.
Sol
from sortedcontainers import SortedList
class Twitter:
def __init__(self):
self.u2ps = defaultdict(list)
self.u2us = defaultdict(set)
self.tick = 10000
def getUser(self,userId):
if userId not in self.u2us:
self.u2us[userId].add(userId)
return userId
def postTweet(self, userId: int, tweetId: int) -> None:
self.u2ps[self.getUser(userId)].append((self.tick, tweetId))
self.tick -= 1
def getNewsFeed(self, userId: int) -> List[int]:
hq = SortedList()
for u in self.u2us[userId]:
u = self.u2ps[u]
[hq.add(x) for x in u[max(len(u)-10,0):]]
return [p[1] for p in hq[:10]]
def follow(self, followerId: int, followeeId: int) -> None:
self.u2us[self.getUser(followerId)].add(self.getUser(followeeId))
def unfollow(self, followerId: int, followeeId: int) -> None:
self.u2us[self.getUser(followerId)].discard(self.getUser(followeeId))