355. Design Twitter

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)

你可能感兴趣的:(355. Design Twitter)