leetcode 355. Design Twitter

来源:互联网 发布:java考试系统源代码 编辑:程序博客网 时间:2024/04/27 22:59
constexpr size_t FEED_COUNT = 10;class Twitter {public:    /** Initialize your data structure here. */    Twitter()         :m_time(0)    {    }    /** Compose a new tweet. */    void postTweet(int userId, int tweetId)     {        m_tweets[userId].emplace_back(m_time++,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)     {        std::vector<Tweet> tweets;        for(auto followeeID : m_follows[userId])        {            for(const auto& tweet : m_tweets[followeeID])            {               tweets.push_back(tweet);            }        }        for(const auto& tweet : m_tweets[userId])        {            tweets.push_back(tweet);        }        std::sort(tweets.begin(),tweets.end(),[](const Tweet& a,const Tweet&b){return b.time < a.time;});        std::vector<int> res;        res.reserve(FEED_COUNT);        for(int i = 0;i<FEED_COUNT && i< tweets.size();i++)        {            res.push_back(tweets[i].ID);        }        return res;    }    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */    void follow(int followerId, int followeeId)    {        if(followerId != followeeId)        {            m_follows[followerId].insert(followeeId);        }    }    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */    void unfollow(int followerId, int followeeId)     {        m_follows[followerId].erase(followeeId);    }private:    struct Tweet    {        size_t time;        int ID;        Tweet(const size_t time_t,const int ID_t)            :time(time_t),ID(ID_t)        {        }    };    std::unordered_map<int,std::vector<Tweet>> m_tweets;     std::unordered_map<int,std::unordered_set<int>> m_follows;    size_t m_time;};/** * 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); */
原创粉丝点击