CPP 120ms using RB-Tree(map,set)


  • 0
    Z

    // assume that evey tweet isn't posted in the same time

    class Twitter {
    public:
        /** Initialize your data structure here. */
        int time=INT_MAX;
        unordered_map<int,map<int,int>> userTweets;
        unordered_map<int,unordered_set<int>> userFollow;
        Twitter() {
            
        }
        
        /** Compose a new tweet. */
        void postTweet(int userId, int tweetId) {
            time--;
            userTweets[userId][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) {
            map<int,int> NewsFeed;
            map<int,int> uTweets=userTweets[userId];
            map<int,int>::iterator it;
            int count=0;
            for(it=uTweets.begin();it!=uTweets.end();it++) {
                NewsFeed[it->first]=it->second;
                count++;
                if(count==10) break;
            }
            for(int Follow_userId:userFollow[userId]) {
                map<int,int> tmp_uTweets=userTweets[Follow_userId];
                for(it=tmp_uTweets.begin();it!=tmp_uTweets.end();it++) {
                    if(NewsFeed.size()<10) {
                        NewsFeed[it->first]=it->second;
                    }
                    else {
                        if((--NewsFeed.end())->first<it->first) break;
                        NewsFeed[it->first]=it->second;
                        NewsFeed.erase(--NewsFeed.end());
                    }
                }
            }
            vector<int> res;
            for(it=NewsFeed.begin();it!=NewsFeed.end();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) {
            if(followerId==followeeId) return;
            userFollow[followerId].insert(followeeId);
        }
        
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        void unfollow(int followerId, int followeeId) {
            userFollow[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);
     */
    

Log in to reply
 

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