leetcode-4.13[355. 設計推特](python解法)

題目在這裏插入圖片描述

題解

from collections import defaultdict

class Twitter:
    def __init__(self):
        """
        Initialize your data structure here.
        先說初始化函數,self.tweets是一個字典結構,鍵是userId,值是tweetId的列表,保存每個用戶發表的tweet信息。類似,following         保存每個用戶的關注列表。idd是保持所有tweet時間序的整數,無論哪位用戶發一條tweet前idd都會自增1。
        """
        self.tweets = defaultdict(list)
        self.following = defaultdict(set)
        self.idd = 0

    def postTweet(self, userId: int, tweetId: int) -> None:
        """
        Compose a new tweet.
        """
        self.idd += 1
        self.tweets[userId].append((tweetId, self.idd))

    def follow(self, followerId: int, followeeId: int) -> None:
        """
        Follower follows a followee. If the operation is invalid, it should be a no-op.
        """
        self.following[followerId].add(followeeId)  #這裏採用的集合,存在值則不add,不存在則add

    def unfollow(self, followerId: int, followeeId: int) -> None:
        """
        Follower unfollows a followee. If the operation is invalid, it should be a no-op.
        """
        if followeeId in self.following[followerId]:
            self.following[followerId].remove(followeeId)

    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.
        """
        users = self.following[userId]
        users.add(userId)
        tmp_data = [self.tweets[item][-10:] for item in users] # 取出每個用戶(包括自己)的最後發佈的10條推文
        tmp_data = [tmp for item in tmp_data for tmp in item] # 將每個用戶的前10條推文都整合一起
        tmp_data.sort(key= lambda a: a[1], reverse=True) # 根據idd從大到小排序
        return [item[0] for item in tmp_data[:10]]  # 取出推文


# 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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章