Design Twitter解题报告

来源:互联网 发布:淘宝那家零食店好 编辑:程序博客网 时间:2024/04/28 07:10

https://leetcode.com/problems/design-twitter/

这道题是让我们实现一个简单的tweet,就是实现follow用户,unfollow用户和获取最新tweet的功能。最复杂的获取最新tweet。
我们用一个计数器表示时间,每发一条tweet,时间加一,时间越大表示距离现在越近。这里我们维护一个大小为10的map,遍历用户关注的每一个用户发的每一个帖子。

class Twitter {private:    int cnt=0;    unordered_map<int,set<int>> friends;    unordered_map<int,map<int,int>> tweets;public:    /** Initialize your data structure here. */    Twitter() {        cnt=0;    }        /** Compose a new tweet. */    void postTweet(int userId, int tweetId) {        follow(userId,userId);        tweets[userId].insert(pair<int,int>(cnt++,tweetId));    }        /** 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) {        vector<int> res;        map<int,int> top10;        for(auto it=friends[userId].begin();it!=friends[userId].end();it++){            int t=*it;            for(auto a=tweets[t].begin();a!=tweets[t].end();a++){                if(top10.size()>0&&top10.begin()->first>a->first&&top10.size()>10) break;//这里判断,因为map是排序的,是从小到大排序,如果first比a的都大,说明first比a更近,所以就不用接着比较了。                top10.insert(pair<int,int>(a->first,a->second));                if(top10.size()>10) top10.erase(top10.begin());            }        }        for (auto it = top10.rbegin(); it != top10.rend(); ++it) {            res.push_back(it->second);        }        return res;    }        /** 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(followerId!=followeeId){            friends[followerId].erase(followeeId);        }    }};/** * 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
原创粉丝点击