[Leetcode] 355. Design Twitter 解题报告

题目

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:

  1. postTweet(userId, tweetId): Compose a new tweet.
  2. getNewsFeed(userId): 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.
  3. follow(followerId, followeeId): Follower follows a followee.
  4. unfollow(followerId, followeeId): Follower unfollows a followee.

Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

思路

我觉得这是一道很好的design类题目。下面说说我们的实现:

首先定义User数据结构,每个User需要有一个粉丝群(followee),还有他所发表的一系列tweets,每条tweets需要记录tweet id和发表时间post time。最后还需要定义一个全局变量post time,用来标记当前时间。

函数设计中最关键的是vector<int> getNewsFeed(int userId)。我们采用了优先级队列来实现(用heap也可以)。首先将当前用户以及所有他关注的人的tweets都加入该优先队列中,然后从中取出最新的前10条返回。这是最朴素的一个实现,还有各种可能的优化方法,例如:1)仅取每个用户最新发表的10条tweets(如果不足10条则取所有),作为加入优先队列的备选;2)采用倒序的优先队列,也就是把最老的tweet放在优先队列的队首。这样的好处是,如果队列的大小达到10,每次加入新tweet之前先和队首元素比较,如果发现比队首元素的发表时间靠前,则忽略;否则就把队首元素出列,然后加入新的tweet。当然在最后返回之前别忘了对结果进行逆序。有兴趣的读者可以自己实现,感觉这些优化在面试的时候可以加分。

代码

class Twitter {
public:
    /** Initialize your data structure here. */
    Twitter() {
        post_time = 0;
    }
    
    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        users[userId].tweets.push_back(make_pair(tweetId, post_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) {
        auto cmp = [](pair<int,int> a, pair<int,int> b) { return a.second < b.second; };
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> que(cmp);  
        for(auto val: users[userId].tweets) {       // push the current user's tweets
            que.push(val);  
        }
        for(auto val1: users[userId].followee) {    // push the current user's followee's tweets
            for(auto val2: users[val1].tweets) {
                que.push(val2); 
            }
        }
        vector<int> result;  
        while(!que.empty()) {  
            result.push_back(que.top().first);  
            que.pop();  
            if(result.size() == 10) {
                break;  
            }
        }  
        return result;  
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        if(followerId != followeeId)  
            users[followerId].followee.insert(followeeId); 
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        users[followerId].followee.erase(followeeId); 
    }
private:
    struct User {  
        set<int> followee;  
        vector<pair<int, int>> tweets;      // the first is tweet id, and the second is post time
    };  
    unordered_map<int, User> users;         // the set of users
    int post_time = 0;  
};

/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter obj = new Twitter();
 * obj.postTweet(userId,tweetId);
 * vector<int> 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、付费专栏及课程。

余额充值