C++ simple code using stl


  • 6
    B
    class Twitter {
    private:
        struct P {
            int id, ref;
            P(int i = 0, int j = 0) :id(i), ref(j) {}
            inline bool operator<(const P &a) const { return ref > a.ref; }
        };
    public:
        Twitter() { time = 1; }
        void postTweet(int userId, int tweetId) {
            userPost[userId].insert(P(tweetId, time++));
            userFollow[userId].insert(userId);
        }
        vector<int> getNewsFeed(int userId) {
            q.clear();
            vector<int> res;
            for(auto &r: userFollow[userId]) {
                int n = userPost[r].size();
                auto it = userPost[r].begin();
                n = min(n, 10);
                while(n--) {
                    if(q.size() < 10) {
                        q.insert(*it++);
                    } else {
                        auto c = q.end();
                        if(*it < *--c) {
                            q.erase(c);
                            q.insert(*it++);
                        }
                    }
                }
            }
            for(auto &r: q) res.push_back(r.id);
            return res;
        }
        void follow(int followerId, int followeeId) {
            userFollow[followerId].insert(followeeId);
        }
        void unfollow(int followerId, int followeeId) {
            if(followerId == followeeId) return;
            userFollow[followerId].erase(followeeId);
        }
    private:
        int time;
        set<P> q;
        unordered_map<int, set<int>> userFollow;
        unordered_map<int, set<P>> userPost;
    };

Log in to reply
 

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