Very simple and easy understanding solution using c++


  • 0
    D
    class Tweet{
    public:
        int date;
        int tweetId;
        Tweet(int date, int id):date(date),tweetId(id){}
        bool operator < (const Tweet &t) const {
            if (tweetId == t.tweetId){
                return false;
            }
            return !(date < t.date);
        }
    };
    
    class Twitter {
    private:
        unordered_map<int,set<Tweet>>user_tweet;
        unordered_map<int,set<int>>flwer_flwee;
        unordered_set<Tweet> y;
        static int date;
    public:
        /** Initialize your data structure here. */
        Twitter() {
            
        }
        
        /** Compose a new tweet. */
        void postTweet(int userId, int tweetId) {
            Tweet t(date,tweetId);
            date++;
            user_tweet[userId].insert(t);
        }
        
        /** 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) {
            set<Tweet> res;
            vector<int> result;
            for(auto &id : flwer_flwee[userId]){
                auto sett = user_tweet[id];
                for(auto &tet : sett){
                    res.insert(tet);
                }
            }
            for(auto &tet : user_tweet[userId]){
                res.insert(tet);
            }
            int i = 0;
            for(auto it = res.begin(); it != res.end() && i < 10; it++,i++){
                
                result.push_back((*it).tweetId);
            }
            return result;
        }
        
        /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
        void follow(int followerId, int followeeId) {
            flwer_flwee[followerId].insert(followeeId);
        }
        
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        void unfollow(int followerId, int followeeId) {
            flwer_flwee[followerId].erase(followeeId);
        }
    };
    int Twitter :: date = 0;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.