The title
Design a simplified version of Twitter that allows users to send tweets, follow/unfollow other users, and see the last 10 tweets of those who follow them (including themselves).
Implement the Twitter class:
Void postTweet(int userId, int tweetId) creates a new tweet based on the given tweetId and userId. Each time this function is called, a different tweetId is used. List getNewsFeed(int userId) Retrieves the ids of the last 10 tweets in the current user’s newsfeed. Every item in the news feed must be a tweet from someone the user follows or from the user himself. Tweets must be sorted chronologically from most recent to most distant. Void Follow (int followerId, int followeeId) The user whose ID is followerId follows the user whose ID is followeeId. Void unfollow(int followerId, int followeeId) User followerId does not follow user followeeId.
Source: force buckle
implementation
Initialize the
var Twitter = function() {
this.article = [] // Store all the articles in the format of [user ID, article ID]
this.followMap = new Map(a)// Store user concerns
};
Copy the code
post
Twitter.prototype.postTweet = function(userId, tweetId) {
// The article pushes directly
this.article.push([userId, tweetId])
// Put yourself in the user relationship
this.followMap.set(userId, (this.followMap.get(userId) || new Set()).add(userId))
};
Copy the code
Access to tweet
Twitter.prototype.getNewsFeed = function(userId) {
let res = [] // Store the result
let users = this.followMap.get(userId) // Get the user relationship
// Get only the last 10 entries
for (let i = this.article.length - 1, j = 0; i >= 0 && j < 10; i--) {
let x = this.article[i] // [user ID, article ID]
// If the publisher of this article is in the user relationship
if (users.has(x[0])) {
j++
res.push(x[1])}}return res
};
Copy the code
Focus on
If you have a pre-existing user relationship, you just add followers,
Otherwise, you need to add yourself and followers
Twitter.prototype.follow = function(followerId, followeeId) {
// If there is a previous user relationship, you just need to add followers
if (this.followMap.get(followerId)) {
this.followMap.get(followerId).add(followeeId)
// Otherwise you need to add yourself and followers
} else {
this.followMap.set(followerId, new Set([followerId, followeeId]))
}
};
Copy the code
Cancel the attention
You just need to delete it from the user relationship
Twitter.prototype.unfollow = function(followerId, followeeId) {
this.followMap.get(followerId).delete(followeeId)
};
Copy the code