zoukankan      html  css  js  c++  java
  • leetcode 355 Design Twitter

    class Twitter {
        unordered_map<int,deque<pair<int,int>>> uid_tid;//deque is double-ended queue
        unordered_map<int,unordered_set<int>> uid_fid;
        int times=0;public:
        /** Initialize your data structure here. */
        Twitter() {
            
        }
        
        /** Compose a new tweet. */
        void postTweet(int userId, int tweetId) {
            if(uid_tid[userId].size()==10) uid_tid[userId].pop_front();
            uid_tid[userId].push_back({tweetId,times++});
        }
        
        /** 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>> vec(uid_tid[userId].begin(),uid_tid[userId].end());
            for(auto follow:uid_fid[userId]) {
                vec.insert(vec.end(),uid_tid[follow].begin(),uid_tid[follow].end());
            }
            sort(vec.begin(),vec.end(),[](pair<int,int>&a,pair<int,int>&b){return a.second>b.second;});
            vector<int> re;
            int size=vec.size()<10?vec.size():10;
            for(int i=0;i<size;++i) {
                re.push_back(vec[i].first);
            }
            return re;
        }
        
        /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
        void follow(int followerId, int followeeId) {
            if(followerId==followeeId) return;
            if(uid_fid[followerId].find(followeeId)!=uid_fid[followerId].end()) return;
            uid_fid[followerId].insert(followeeId);
        }
        
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        void unfollow(int followerId, int followeeId) {
            uid_fid[followerId].erase(followeeId);
        }
    };
    
    /**
     * Your Twitter object will be instantiated and called as such:
     * Twitter* obj = new Twitter();
     * obj->postTweet(userId,tweetId);
     * vector<int> param_2 = obj->getNewsFeed(userId);
     * obj->follow(followerId,followeeId);
     * obj->unfollow(followerId,followeeId);
     */
  • 相关阅读:
    高精度计算模板
    P1108 低价购买 [DP][统计方案]
    POJ3349 Snowflake Snow Snowflakes [哈希]
    P1312 Mayan游戏 [深搜][模拟]
    P1378 油滴扩展[深搜]
    P1514 引水入城[搜索,线段覆盖]
    TYVJ1391 走廊泼水节
    【BZOJ1196】公路修建问题
    【BZOJ3624】免费道路
    【BZOJ2429】聪明的猴子
  • 原文地址:https://www.cnblogs.com/LiuQiujie/p/12596791.html
Copyright © 2011-2022 走看看