LeetCode 355. Diseño de Twitter (hash map + set)

1. Título

Diseñe una versión simplificada de Twitter, que permita a los usuarios enviar tweets, seguir / dejar de seguir a otros usuarios y ver los últimos diez tweets de seguidores (incluidos ellos mismos). Su diseño debe admitir las siguientes funciones:

  • postTweet(userId, tweetId): Crea un nuevo tweet
  • getNewsFeed(userId): Recupera los diez tweets más recientes. Cada tweet debe ser enviado por la persona interesada por el usuario o el propio usuario. Los tweets deben clasificarse en orden cronológico a partir del más reciente.
  • follow(followerId, followeeId): Seguir a un usuario
  • unfollow(followerId, followeeId): Dejar de seguir a un usuario
示例:

Twitter twitter = new Twitter();

// 用户1发送了一条新推文 (用户id = 1, 推文id = 5).
twitter.postTweet(1, 5);

// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
twitter.getNewsFeed(1);

// 用户1关注了用户2.
twitter.follow(1, 2);

// 用户2发送了一个新推文 (推文id = 6).
twitter.postTweet(2, 6);

// 用户1的获取推文应当返回一个列表,其中包含两个推文,id分别为 -> [6, 5].
// 推文id6应当在推文id5之前,因为它是在5之后发送的.
twitter.getNewsFeed(1);

// 用户1取消关注了用户2.
twitter.unfollow(1, 2);

// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
// 因为用户1已经不再关注用户2.
twitter.getNewsFeed(1);

Fuente: LeetCode
Enlace: https://leetcode-cn.com/problems/design-twitter Los
derechos de autor pertenecen a la Red de Deducción. Comuníquese con la autorización oficial para la reimpresión comercial e indique la fuente de la reimpresión no comercial.

2. Resolución de problemas

struct cmp
{
    bool operator()(const vector<int> &a, const vector<int> &b) const
    {
        return a[0] < b[0];
    }
};
class Twitter {
    unordered_map<int,unordered_set<int>> m;//id,关注的人
    set<vector<int>,cmp> tweet;//time, 推文id,用户id
    int time = 0;
    int count;
    vector<int> ans;
public:
    /** Initialize your data structure here. */
    Twitter() {}
    
    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        tweet.insert({time++, tweetId, userId});
    }
    
    /** 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) {
        count = 10;
        ans.clear();
        for(auto it = tweet.rbegin(); it != tweet.rend() && count; ++it)
        {
            if((*it)[2]==userId || m[userId].count((*it)[2]))
            {
                ans.push_back((*it)[1]);
                count--;
            }
        }
        return ans;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        m[followerId].insert(followeeId);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        m[followerId].erase(followeeId);
    }
};

532 ms 21,7 MB

Publicado 839 artículos originales · elogiado 2083 · 440,000 vistas +

Supongo que te gusta

Origin blog.csdn.net/qq_21201267/article/details/105480197
Recomendado
Clasificación