python solution easy to understand


  • 0
    P
    from collections import defaultdict
    
    
    class Twitter(object):
        def __init__(self):
            
            self.dictFollow = defaultdict(list)  # dictFollow[follower] = [followee1,folloee2......] 
            self.dictTwitter = defaultdict(list) # dictTwitter[posterId] = [twitterId1,twitter2......]
            self.time = 1  # 微博时间,每发表一篇微博,时间就加1 
            self.twitterWithTime = {}  # twitterWithTime[twitterId] = time
    
        def postTweet(self, userId, tweetId):
            
         
            self.dictTwitter[userId].append(tweetId)
            self.twitterWithTime[tweetId]=self.time
            self.time+=1
    
        def getNewsFeed(self, userId):
            
            result = []
            for i in self.dictFollow[userId]:
                for j in self.dictTwitter[i]:
                    result.append(j)
            for i in self.dictTwitter[userId]:
                result.append(i)
            return sorted(result,key=lambda c:self.twitterWithTime[c],reverse=True)[:10]
    
        def follow(self, followerId, followeeId):
           
           
            if followeeId not in self.dictFollow[followerId] and followeeId!=followerId:
                self.dictFollow[followerId].append(followeeId)
    
        def unfollow(self, followerId, followeeId):
           
            if followeeId in self.dictFollow[followerId]:
                self.dictFollow[followerId].remove(followeeId)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.