355. 设计推特

设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文。你的设计需要支持以下的几个功能:

  1. postTweet(userId, tweetId): 创建一条新的推文
  2. getNewsFeed(userId): 检索最近的十条推文。每个推文都必须是由此用户关注的人或者是用户自己发出的。推文必须按照时间顺序由最近的开始排序。
  3. follow(followerId, followeeId): 关注一个用户
  4. unfollow(followerId, followeeId): 取消关注一个用户

示例:

Twitter twitter = new Twitter();

// 用户1发送了一条新推文 (用户id = 1, 推文id = 5).
twitter.postTweet(1, 5);

// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
twitter.getNewsFeed(1);

// 用户1关注了用户2.
twitter.follow(1, 2);

// 用户2发送了一个新推文 (推文id = 6).
twitter.postTweet(2, 6);

// 用户1的获取推文应当返回一个列表,其中包含两个推文,id分别为 -> [6, 5].
// 推文id6应当在推文id5之前,因为它是在5之后发送的.
twitter.getNewsFeed(1);

// 用户1取消关注了用户2.
twitter.unfollow(1, 2);

// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
// 因为用户1已经不再关注用户2.
twitter.getNewsFeed(1);

思路:需要用哈希表来做建立用户和其所有好友之间的映射,建立用户和其所有消息之间的映射,建立每个消息和其时间点cnt之间的映射。可以用一个整型变量time来模拟时间点,每发一个消息,time自增1。最近的十条推文可以用小顶堆优先队列来控制。当队列里的元素数量小于10,或者当前推文发布时间大于队顶推文发布时间,就把当前推文塞入到队列中。

优先队列的定义:

priority_queue<int>q;   //通过操作,按照元素从大到小的顺序出队

priority_queue<int, vector<int>, greater<int> >q;  //通过操作,按照元素从小到大的顺序出队

class Twitter {
private:
    int time;
    unordered_map<int, unordered_set<int> >friends;
    unordered_map<int, unordered_map<int,int> >tweets;

public:
    /** Initialize your data structure here. */
    Twitter() {
        time=0;
    }
    
    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        follow(userId, userId);//因为检索的10条也包括用户自己发出的
        tweets[userId][tweetId]=time++;
    }
    
    /** 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. */
    vector<int> getNewsFeed(int userId) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> >q;//为了让早前发布的推文出队列
        vector<int>re;
        for(auto x: friends[userId]){
            for(auto y:tweets[x]){
                if(q.size()<10 || q.top().first < y.second) q.push({y.second, y.first});
                if(q.size()>10) q.pop();
            }
        }
        while(!q.empty()){
            re.insert(re.begin(), q.top().second);
            q.pop();
        }
        return re;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        friends[followerId].insert(followeeId);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        if(followeeId!=followerId)
        friends[followerId].erase(followeeId);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值