[Serie Leetcode] [algoritmo] [medio] diseño Twitter

Titulo:

Enlace del título:  https://leetcode-cn.com/problems/design-twitter/

 

Ideas para resolver problemas:

hash + lista doblemente vinculada

La clave de la tabla hash es el usuario, y el valor es la lista de usuarios que sigue el usuario

La lista doblemente vinculada almacena los tweets enviados por el usuario, el frente es el último enviado, el reverso es el más antiguo

Por conveniencia, pongo los tweets enviados por todos en una lista doblemente vinculada

De hecho, cada usuario debe crear una lista doblemente vinculada y luego obtener el contenido de Twitter, usar el método de  fusionar K listas vinculadas ordenadas  , obtener los últimos 10 Twitters y luego regresar

 

La razón para usar una lista doblemente vinculada es porque puede haber una operación de eliminación, por lo que la lista doblemente vinculada fue diseñada

Para este problema, la lista unidireccional debe cumplir las condiciones

 

Implementación de código:

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)

 

Publicado 115 artículos originales · ganó 11 · visitado 1675

Supongo que te gusta

Origin blog.csdn.net/songyuwen0808/article/details/105491174
Recomendado
Clasificación