topic:
Title link: https://leetcode-cn.com/problems/design-twitter/
Problem-solving ideas:
hash + doubly linked list
The key of the hash table is the user, and the value is the user list that the user follows
The doubly linked list stores the tweets sent by the user, the front is the latest sent, the back is the older
For convenience, I put the tweets sent by everyone into a doubly linked list
In fact, each user should create a doubly linked list, and then get the Twitter content, use the method of merging K sorted linked lists , get the latest 10 Twitters, and then return
The reason for using a doubly linked list is because there may be a delete operation, so the doubly linked list was just designed
For this problem, one-way linked list should meet the conditions
Code:
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)