zoukankan      html  css  js  c++  java
  • LeetCode "Design Twitter"

    A mix of hashmap, list and heap.

    struct Tw
    {
        Tw(long long pts, int tid)
        {
            ts = pts;
            tweetid = tid;
        }
        long long ts;
        int tweetid;
    };
    struct Cmp
    {
        bool operator()(const Tw &a, const Tw &b)
        {
            return a.ts > b.ts;
        }
    };
    class Twitter {
        long long ts;
        unordered_map<int, unordered_set<int>> fllw;
        unordered_map<int, list<Tw>> twts;
    public:
        /** Initialize your data structure here. */
        Twitter() {
            ts = 0;
        }
        
        /** Compose a new tweet. */
        void postTweet(int userId, int tweetId) {
            twts[userId].push_back({ts ++, tweetId});
            if(twts[userId].size() > 10) twts[userId].pop_front();
        }
        
        /** 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) {
            priority_queue<Tw, vector<Tw>, Cmp> q;
            for(auto uid : fllw[userId])
            {
                for(auto &tw : twts[uid])
                {
                    q.push(tw);
                    if(q.size() > 10) q.pop();
                }
            }
            for(Tw &tw : twts[userId])
            {
                q.push(tw);
                if(q.size() > 10) q.pop();
            }
                
            vector<int> ret;
            while(!q.empty())
            {
                ret.push_back(q.top().tweetid);
                q.pop();
            }
            reverse(ret.begin(), ret.end());
            return ret;
        }
        
        /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
        void follow(int followerId, int followeeId) {
            if (followerId != followeeId)
                fllw[followerId].insert(followeeId);
        }
        
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        void unfollow(int followerId, int followeeId) {
            fllw[followerId].erase(followeeId);
        }
    };
    View Code
  • 相关阅读:
    线性回归和 逻辑回归 的思考(参考斯坦福 吴恩达的课程)
    数据结构算法基础-内部排序算法
    机器学习《test》
    day1.接口测试(概念、Postman、SoapUI、jmeter)
    SQL2000 3核6核 CUP 安装SP4
    SQL常用语句
    SQL SERVER 2000数据库置疑处理
    常用终端命令
    c++ 位操作
    计算机为什么用补码存储数据?
  • 原文地址:https://www.cnblogs.com/tonix/p/5622059.html
Copyright © 2011-2022 走看看