LeetCode Design Twitter



Leetcode Design Twitter



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

postTweet(userId, tweetId): Create a new tweet getNewsFeed(userId): Retrieve the last ten tweets. Each tweet must be sent by the person the user is following or by the user. Tweets must be sorted by chronological order from the most recent start. Follow(followerId, followeeId): follow a user Unfollow(followerId, followeeId): Unfollow a user

例:



Twitter twitter = new Twitter() // User 1 sent a new tweet (user id = 1, tweet id = 5). twitter.postTweet(1, 5) // User 1's get tweet should return a list containing a tweet with an id of 5. twitter.getNewsFeed(1) // User 1 is following user 2. twitter.follow(1, 2) // User 2 sent a new tweet (tweet id = 6). twitter.postTweet(2, 6) // User 1's get tweet should return a list containing two tweets with id -> [6, 5]. // The tweet id6 should be before the tweet id5 because it was sent after 5. twitter.getNewsFeed(1) // User 1 unfollowed user 2. twitter.unfollow(1, 2) // User 1's get tweet should return a list containing a tweet with an id of 5. // Because User 1 is no longer interested in User 2. twitter.getNewsFeed(1)

アイデアの分析:この質問は、情報を格納するための適切なデータ構造を選択することです。リスト、マップコンテナを使用して支援します。

class Twitter { private: List twitterNews//for storing news Map followMap//followMap[i][j] == true means i is following j public: /** Initialize your data structure here. */ Twitter() { } /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { / / Every time is inserted in front twitterNews.insert(twitterNews.begin(), pair(userId, tweetId)) } /** 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 getNewsFeed(int userId) { vector result list::iterator it = twitterNews.begin() //Get up to 10 at most while (it != twitterNews.end() && result.size() first == userId || followMap[userId][it->first]){ result.push_back(it->second) } it++ } return result } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { followMap[followerId][followeeId] = true//Follow } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ void unfollow(int followerId, int followeeId) { followMap[followerId][followeeId] = false//Unfollow } } /** * Your Twitter object will be instantiated and called as such: * Twitter obj = new Twitter() * obj.postTweet(userId,tweetId) * vector param_2 = obj.getNewsFeed(userId) * obj.follow(followerId,followeeId) * obj.unfollow(followerId,followeeId) */

画像
なぜそんなに遅いのかわかりませんが、彼らは私と同じ基本を書いているように感じます。 。 。 。