【每日一题】335 设计推特

2020.04.13
在这里插入图片描述
是一道系统设计类题目。利用数据结构实现功能。

基本的设计框架如下,有一个列表存放目前所有的推文,包括了发送人和推文内容。另外需要维护一个字典,字典的键是每个人的id,存储的值是一个集合,包括了关注的朋友。

每次获取推文,需要按照发布的新旧程度查找符合关注列表的。

class Twitter:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.dic = {}
        self.deque = []
        

    def postTweet(self, userId: int, tweetId: int) -> None:
        """
        Compose a new tweet.
        """
        content = [userId, tweetId]
        self.deque.append(content)
        

    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.
        """
        dicuser = self.dic.get(userId, set())
        dicuser.add(userId)
        count = 10
        ans = []
        for item in self.deque[::-1]:
            if item[0] in dicuser:
                ans.append(item[1])
                count -= 1
                if count == 0:
                    return ans
        return ans

    def follow(self, followerId: int, followeeId: int) -> None:
        """
        Follower follows a followee. If the operation is invalid, it should be a no-op.
        """
        self.dic[followerId] = self.dic.get(followerId, set())
        self.dic[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 followerId not in self.dic:
            return 
        self.dic[followerId].discard(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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值