题目
设计一个简化版的推特(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 的用户。
题解
- 用userAndMess保存用户自己发的推特
- user用来保存用户推特ID,其中user的key是用户自身id,value是
[用户自身ID,用户关注ID] - index用来标记当前推特发布的时间,因为题目要求
推文必须按照时间顺序由最近到最远排序 。 - postTweet方法中,将用户放在user中,将用户推送的推特账号放在userAndMess中,并标记推送时间
- getNewsFeed 获取推特函数中,根据入参在user获取推特ID,枚举user中推特ID在userAndMess的数据,合并到数组中,取前10位
- follow、unfollow就比较简单了,在user中删除或者添加对应的推特ID即可
代码
var Twitter = function () {
this.users = {}
this.userAndMess = {}
this.index = 0
}
Twitter.prototype.postTweet = function (userId, tweetId) {
if (this.users[userId] === undefined) {
this.users[userId] = [userId]
}
this.index += 1
const idx = this.index
if (this.userAndMess[userId] === undefined) {
this.userAndMess[userId] = [[idx, tweetId]]
} else {
this.userAndMess[userId].unshift([idx, tweetId])
}
}
Twitter.prototype.getNewsFeed = function (userId) {
const array = this.users[userId]
if (Boolean(array)) {
let atotal = []
for (let i = 0; i < array.length; i++) {
const key = array[i]
const messArr = this.userAndMess[key]
if (Array.isArray(messArr)) {
atotal = atotal.concat(messArr.slice(0, 10))
}
}
atotal.sort((a, b) => b[0] - a[0])
const result = atotal.slice(0, 10).map((v) => v[1])
return result
} else {
return []
}
}
Twitter.prototype.follow = function (followerId, followeeId) {
if (followerId === followeeId) return
if (this.users[followerId] === undefined) {
this.users[followerId] = [followerId, followeeId]
} else {
const array = this.users[followerId]
if (!array.includes(followeeId)) {
this.users[followerId].unshift(followeeId)
}
}
}
Twitter.prototype.unfollow = function (followerId, followeeId) {
if (followerId === followeeId) return
if (this.users[followerId] === undefined) {
} else {
const array = this.users[followerId]
if (array.includes(followeeId)) {
const index = array.indexOf(followeeId)
array.splice(index, 1)
}
}
}