難度:中等
題目內(nèi)容:
設(shè)計(jì)一個簡化版的推特(Twitter),可以讓用戶實(shí)現(xiàn)發(fā)送推文,關(guān)注/取消關(guān)注其他用戶,能夠看見關(guān)注人(包括自己)的最近十條推文。你的設(shè)計(jì)需要支持以下的幾個功能:
postTweet(userId, tweetId): 創(chuàng)建一條新的推文
getNewsFeed(userId): 檢索最近的十條推文。每個推文都必須是由此用戶關(guān)注的人或者是用戶自己發(fā)出的。推文必須按照時間順序由最近的開始排序。
follow(followerId, followeeId): 關(guān)注一個用戶
unfollow(followerId, followeeId): 取消關(guān)注一個用戶
示例:
Twitter twitter = new Twitter();
// 用戶1發(fā)送了一條新推文 (用戶id = 1, 推文id = 5).
twitter.postTweet(1, 5);
// 用戶1的獲取推文應(yīng)當(dāng)返回一個列表,其中包含一個id為5的推文.
twitter.getNewsFeed(1);
// 用戶1關(guān)注了用戶2.
twitter.follow(1, 2);
// 用戶2發(fā)送了一個新推文 (推文id = 6).
twitter.postTweet(2, 6);
// 用戶1的獲取推文應(yīng)當(dāng)返回一個列表,其中包含兩個推文,id分別為 -> [6, 5].
// 推文id6應(yīng)當(dāng)在推文id5之前,因?yàn)樗窃?之后發(fā)送的.
twitter.getNewsFeed(1);
// 用戶1取消關(guān)注了用戶2.
twitter.unfollow(1, 2);
// 用戶1的獲取推文應(yīng)當(dāng)返回一個列表,其中包含一個id為5的推文.
// 因?yàn)橛脩?已經(jīng)不再關(guān)注用戶2.
twitter.getNewsFeed(1);
題解:
看著字挺多,不過一步一步來其實(shí)超簡單
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.followList = {}
self.Tweetlist = []
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
self.Tweetlist.append([userId,tweetId])
def getNewsFeed(self, userId: int) -> List[int]:
"""
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.
"""
r = []
for i in range(len(self.Tweetlist)-1,max(0,len(self.Tweetlist)-10)-1,-1):
if self.Tweetlist[i][0] == userId:#自己發(fā)的
r.append(self.Tweetlist[i][1])
else:
try:
if self.Tweetlist[i][0] in self.followList[userId]:#關(guān)注的人發(fā)的
r.append(self.Tweetlist[i][1])
except:
pass
return r
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
try :
self.followList[followerId].append(followeeId)
except:
self.followList[followerId] = [followeeId]
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
try:
self.followList[followerId].remove(followeeId)
except:
pass
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)