【Leetcodeシリーズ】【アルゴリズム】【中】デザインTwitter

タイトル:

タイトルリンク:https//leetcode-cn.com/problems/design-twitter/

 

問題解決のアイデア:

ハッシュ+二重リンクリスト

ハッシュテーブルのキーはユーザーであり、値はユーザーがフォローするユーザーリストです

二重にリンクされたリストには、ユーザーが送信したツイートが保存されます。表は最後に送信されたもので、裏は古いものです

便宜上、みんなから送信されたツイートを二重にリンクされたリストに入れました

実際、各ユーザーは二重にリンクされたリストを作成してからTwitterコンテンツを取得し、Kソートされたリンクリストマージする方法を使用して 、最新の10件のTwitterを  取得してから返す必要があります。

 

二重リンクリストを使用する理由は、削除操作が存在する可能性があるため、二重リンクリストは設計されただけです

この問題の場合、一方向リンクリストは条件を満たす必要があります

 

コードの実装:

class Node:
    def __init__(self, user_id, tweet_id, pre = None, nxt = None):
        self.user_id = user_id
        self.tweet_id = tweet_id
        self.pre = pre
        self.nxt = nxt        

class Twitter:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.head = Node('head', 'head')
        self.tail = Node('tail', 'tail')
        self.head.next = self.tail
        self.tail.prev = self.head
        self.rec = collections.defaultdict(dict)
        

    def postTweet(self, userId: int, tweetId: int) -> None:
        """
        Compose a new tweet.
        """
        node = Node(userId, tweetId)
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node       
        

    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.
        """
        curr_head = self.head
        res = []
        while curr_head.next is not self.tail:
            if curr_head.next.user_id in self.rec[userId] or curr_head.next.user_id == userId:
                res.append(curr_head.next.tweet_id)
                
            if len(res) == 10:
                break
                
            curr_head = curr_head.next
                
        return res
        

    def follow(self, followerId: int, followeeId: int) -> None:
        """
        Follower follows a followee. If the operation is invalid, it should be a no-op.
        """
        self.rec[followerId][followeeId] = 1        

    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 in self.rec and followeeId in self.rec[followerId]:
            self.rec[followerId].pop(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)

 

115の元の記事を公開 11を獲得 1675を訪問

おすすめ

転載: blog.csdn.net/songyuwen0808/article/details/105491174