46ms C++ O(N) solution with hash map + list, beat 100%

  • 0

    Instead collecting tweets from all followers (here it means people that current user follows including self) and put them to one list and sort, we can use the merge member function of list container to do a merge sort for at most 10 elements. Comparing to 10 * N * log (10N)* O(NlogN), the time complexity of merge sort here is (N-1) * 10 * 2, i.e. O(N) (N is the number of followers). This is more efficient when N is large.

    class Twitter {
        typedef pair<int, int> Tweet;
        /** Initialize your data structure here. */
        Twitter() : time_(0) {
        /** Compose a new tweet. */
        void postTweet(int userId, int tweetId) {
            tweets[userId].emplace_back(++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) {
            list<list<Tweet>> feeds;
            for (int f : followers[userId]) {
                int n = tweets[f].size() > 10 ? 10 : tweets[f].size();
                if (n == 0) continue;
                feeds.push_back(list<Tweet>(tweets[f].rbegin(), tweets[f].rbegin() + n));
            while (feeds.size() > 1) {
                feeds.front().merge(feeds.back(), [](Tweet a, Tweet b) {return a.first > b.first;});
                if (feeds.front().size() > 10) feeds.front().resize(10);
            vector<int> res;
            if (feeds.size() > 0) {
                for (auto x : feeds.front()) res.push_back(x.second);
            return res;
        /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
        void follow(int followerId, int followeeId) {
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        void unfollow(int followerId, int followeeId) {
            if (followerId == followeeId) return;
        unordered_map<int, unordered_set<int>> followers;
        unordered_map<int, vector<Tweet>> tweets;
        int time_;

Log in to reply

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