Short and easy code for getNewsFeed(),c++,beats 91%


  • 0
    X

    It is worth explaining the code of getNewsFeed() here. I concatenate all the tweets from the user herself or the user she followed in a larger vector(named as curr), then initialize the max-heap with curr, this way it makes the worst complexity as o(10lgn) rather than o(nlgn) if we push the element in max-heap one by one.

    class Twitter {
        unordered_map<int,unordered_set<int>> following;
        unordered_map<int,vector<pair<int,int>>> tweets;
        int count;//used to indicate the time stamp, and used by max-heap to sort the most recent tweets.
    public:
        /** Initialize your data structure here. */
        Twitter() {
            count=0;
        }
        
        /** Compose a new tweet. */
        void postTweet(int userId, int tweetId) {
            count++;
            following[userId].insert(userId);
            tweets[userId].push_back({count,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) {
            vector<pair<int,int>> curr;
            for(auto it=following[userId].begin();it!=following[userId].end();it++){
                curr.insert(curr.end(),tweets[*it].begin(),tweets[*it].end());
            }
            priority_queue<pair<int,int>> pq(curr.begin(),curr.end());
            vector<int> res;
            int i=0;
            while(!pq.empty()&&i<10){
                res.push_back(pq.top().second);
                pq.pop();
                i++;
            }
            return res;
        }
        
        /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
        void follow(int followerId, int followeeId) {
            following[followerId].insert(followeeId);
        }
        
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        void unfollow(int followerId, int followeeId){
            if(following.count(followerId)&&following[followerId].count(followeeId)&&followerId!=followeeId)
                following[followerId].erase(followeeId);
        }
    };

  • 1
    L

    @xinqrs

    Unless I'm looking at this wrong, seems like your worst run time is not O(10logn) but still O(nlogn).
    You gathered all your tweets and placed them into a vector.
    Then you pushed them all into a heap. That right there states your worst case is O(nlogn) during insertion.
    If the userId you pulled happens to follow everybody, you will have all tweets in that vector hence O(nlogn) when you push the vector into the heap.
    However, when you pop from the heap it is O(10logn).


Log in to reply
 

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