2020.04.13
是一道系统设计类题目。利用数据结构实现功能。
基本的设计框架如下,有一个列表存放目前所有的推文,包括了发送人和推文内容。另外需要维护一个字典,字典的键是每个人的id,存储的值是一个集合,包括了关注的朋友。
每次获取推文,需要按照发布的新旧程度查找符合关注列表的。
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
self.deque = []
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
content = [userId, tweetId]
self.deque.append(content)
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.
"""
dicuser = self.dic.get(userId, set())
dicuser.add(userId)
count = 10
ans = []
for item in self.deque[::-1]:
if item[0] in dicuser:
ans.append(item[1])
count -= 1
if count == 0:
return ans
return ans
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
self.dic[followerId] = self.dic.get(followerId, set())
self.dic[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId not in self.dic:
return
self.dic[followerId].discard(followeeId)
# 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)