题目
设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近 10 条推文。
实现 Twitter 类:
Twitter() 初始化简易版推特对象 void postTweet(int userId, int tweetId) 根据给定的 tweetId 和 userId 创建一条新推文。每次调用此函数都会使用一个不同的 tweetId 。 List getNewsFeed(int userId) 检索当前用户新闻推送中最近 10 条推文的 ID 。新闻推送中的每一项都必须是由用户关注的人或者是用户自己发布的推文。推文必须 按照时间顺序由最近到最远排序 。 void follow(int followerId, int followeeId) ID 为 followerId 的用户开始关注 ID 为 followeeId 的用户。 void unfollow(int followerId, int followeeId) ID 为 followerId 的用户不再关注 ID 为 followeeId 的用户。
来源:力扣(LeetCode)leetcode-cn.com/problems/de…
解题思路
我们要从两个方面考虑这道题,1、用什么来存数据;2、怎么查询数据
- 数据存储
- 使用数组存储推文,并且用数组长度当作排序序号
- 使用双层 Map 存储关注关系,结构像这样
{1: {2:2, 3:3}}
- 数据查询
- 通过关注关系取出用户能看到的推文用户ID,再去推文列表中过滤,并且按序号排序
代码实现
var Twitter = function() {
this.posts = []
this.follows = new Map()
};
/**
* @param {number} userId
* @param {number} tweetId
* @return {void}
*/
Twitter.prototype.postTweet = function(userId, tweetId) {
this.posts.push({userId, tweetId, sort: this.posts.length})
};
/**
* @param {number} userId
* @return {number[]}
*/
Twitter.prototype.getNewsFeed = function(userId) {
const users = [userId]
if (this.follows.has(userId)) {
const follows = this.follows.get(userId)
follows.forEach(userId => users.push(userId))
}
const result = this.posts.filter(post => users.includes(post.userId))
result.sort((a, b) => b.sort - a.sort)
return result.slice(0, 10).map(item => item.tweetId)
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.follow = function (followerId, followeeId) {
if (!this.follows.has(followerId)) {
this.follows.set(followerId, new Map())
}
this.follows.get(followerId).set(followeeId, followeeId)
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.unfollow = function (followerId, followeeId) {
if (this.follows.has(followerId)) {
this.follows.get(followerId).delete(followeeId)
}
};
如有错误欢迎指出,欢迎一起讨论!