C++ solution, time complexity of getNewsFeed: O(nm)


  • 0
    I

    n is the number of users, m is the largest number of followers among users.

    /** Initialize your data structure here. */
    Twitter() {
        /* empty */
    }
    
    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        tweetList[userId].push_back(seq);
        seqMap[seq++] = 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) {
        set<int> priQueue;
        followList[userId].emplace(userId);
        for (int followeeId : followList[userId]) {
            for (int orderId : tweetList[followeeId]) {
                priQueue.emplace(orderId);
                if (priQueue.size() > 10) priQueue.erase(priQueue.begin());
            }
        }
        followList[userId].erase(followList[userId].find(userId));
        vector<int> newsRecent;
        for (int seqId : priQueue) newsRecent.push_back(seqMap[seqId]);
        reverse(newsRecent.begin(), newsRecent.end());
        return newsRecent;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        followList[followerId].emplace(followeeId);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        auto iter = followList[followerId].find(followeeId);
        if (iter != followList[followerId].end()) followList[followerId].erase(iter);
    }
    
    unordered_map<int, unordered_set<int>> followList;
    unordered_map<int, vector<int>> tweetList;
    unordered_map<int, int> seqMap;    // map order to tweetId
    int seq = 0;

Log in to reply
 

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