LeetCode 355.デザインTwitter(ハッシュマップ+セット)

1.タイトル

Twitterの簡易バージョンを設計します。これにより、ユーザーはツイートを送信したり、他のユーザーをフォロー/フォロー解除したり、フォロワー(自分を含む)の最新の10ツイートを表示したりできます。デザインは次の機能をサポートする必要があります。

  • postTweet(userId, tweetId):新しいツイートを作成
  • getNewsFeed(userId):最新の10件のツイートを取得します。各ツイートは、ユーザーの関係者またはユーザー自身が送信する必要があります。ツイートは、最新のものから時間順に並べ替える必要があります。
  • follow(followerId, followeeId):ユーザーをフォローする
  • unfollow(followerId, followeeId):ユーザーのフォローを解除する
示例:

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);

ソース:LeetCode
リンク:https ://leetcode-cn.com/problems/design-twitter
著作権はDeduction Networkに属しています。商用転載の正式な許可書に連絡し、非商用転載の出典を明記してください。

2.問題解決

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

元の記事839件を公開 2083 年に賞賛 44万回の閲覧+

おすすめ

転載: blog.csdn.net/qq_21201267/article/details/105480197