hugo-blog/content/posts/2020-04-14-leetcode-design-twitter.md
Ching 5ba7024532 feat(content; layouts; static): migrate hexo blog. add new theme fuji.
migrate hexo blog. add new theme fuji.

Signed-off-by: Ching <loooching@gmail.com>
2022-02-07 23:38:40 +08:00

85 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: leetcode-design-twitter
date: 2020-04-14 16:11:41
tags:
- leetcode
categories: leetcode
---
### 355. 设计推特
[题目](https://leetcode-cn.com/problems/design-twitter/)
<!--more-->
做出来倒是很简单,由于没有并发和特别的条件,测试数据量也不大。一开始搞错了,以为传入的 `twitterId` 就是自增的 id结果其实是每条推的内容所以增加了一个计数器去标记 id。
主要的考点应该是 `多路归并` 这个东西。我用的是排序,在数据量大的时候应该会有些问题。
```python
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.tweets = {}
self.followers = {}
self._tid = 0
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
if not self.tweets.get(userId):
self.tweets[userId] = []
self.tweets[userId].append((self._tid, tweetId))
self._tid += 1
def getNewsFeed(self, userId: 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.
"""
foers = self.followers.get(userId, set())
foers = foers.union((userId,))
tweets = []
for fo in foers:
tweets.extend(self.tweets.get(fo, [])[-10:])
return [tw[1] for tw in sorted(tweets, reverse=True)[:10]]
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
if not self.followers.get(followerId):
self.followers[followerId] = set()
self.followers[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
if not self.followers.get(followerId):
self.followers[followerId] = set()
if followeeId in self.followers[followerId]:
self.followers[followerId].remove(followeeId)
#100 ms 19.2 MB
# 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)
```