class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.__number_of_most_recent_tweet=10
self.__followings=collections.defaultdict(set)
self.__messages=collections.defaultdict(list)
self.__time=0
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.__time+=1
self.__messages[userId].append((self.__time,tweetId))
def getNewsFeed(self, userId):
"""
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.
:type userId: int
:rtype: List[int]
"""
max_heap=[]
#push the latest tweet of each user id to the heap, one of them has to be the latest tweet
#time(used for heap sorting) ,userId, curr(keep track of which tweet of this particular user is in the heap)
if self.__messages[userId]:
heapq.heappush(max_heap,(-(self.__messages[userId][-1][0]),userId,0))
for uid in self.__followings[userId]:
if self.__messages[uid]:
heapq.heappush(max_heap,(-self.__messages[uid][-1][0],uid,0))
result=[]
while max_heap and len(result)<self.__number_of_most_recent_tweet:
t, uid,curr=heapq.heappop(max_heap)
#after popping the tweet of this user, push his next tweet on to the heap
nxt=curr+1
if nxt!=len(self.__messages[uid]):
heapq.heappush(max_heap,(-self.__messages[uid][-nxt-1][0],uid,nxt))
result.append(self.__messages[uid][-curr-1][1])
return result
def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
if followerId!=followeeId:
self.__followings[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.__followings[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,followed)
355. Design Twitter
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Design Twitter应用面向对象设计(OO)模拟Twitter的几个功能,分别是: 发推postTweet...
- Question Design a simplified version of Twitter where use...
- My code: reference:https://discuss.leetcode.com/topic/481...