simple C++ solution


  • 1
    Y
    unordered_map<int, unordered_set<int>> graph;
    vector<pair<int, int>> tweets;
    
    Twitter() {}
    
    void postTweet(int userId, int tweetId) {
        tweets.push_back(make_pair(userId, tweetId));
    }
    
    vector<int> getNewsFeed(int userId) {
        vector<int> newsFeed;
        for (int i = tweets.size() - 1; i >= 0 && newsFeed.size() < 10; --i) {
            if (tweets[i].first == userId || graph[userId].find(tweets[i].first) != graph[userId].end()) {
                newsFeed.push_back(tweets[i].second);
            }
        }
        return newsFeed;
    }
    
    void follow(int followerId, int followeeId) {
        if (followerId != followeeId) {
            graph[followerId].insert(followeeId);
        }
    }
    
    void unfollow(int followerId, int followeeId) {
        auto followeeIter = graph[followerId].find(followeeId); 
        if (followerId != followeeId && followeeIter != graph[followerId].end()) {
            graph[followerId].erase(followeeIter);    
        }
    }

Log in to reply
 

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