题目
设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近 10 条推文。
实现 Twitter 类:
Twitter() 初始化简易版推特对象
void postTweet(int userId, int tweetId) 根据给定的 tweetId 和 userId 创建一条新推文。每次调用此函数都会使用一个不同的 tweetId 。
List<Integer>
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 的用户。
先贴代码了,虽然标着困难,感觉不是困难的。。
var Twitter = function() {
this.users = {}
this.max = 10
this.postIndex = 0
};
/**
* @param {number} userId
* @param {number} tweetId
* @return {void}
*/
Twitter.prototype.postTweet = function(userId, tweetId) {
if (!this.users[userId]) this.users[userId] = { heap: [], followeeId: []}
this.users[userId].heap.push({ timemap: this.postIndex++, tweetId })
};
/**
* @param {number} userId
* @return {number[]}
*/
Twitter.prototype.getNewsFeed = function(userId) {
if (!this.users[userId]) return []
const { followeeId } = this.users[userId]
const showHeap = new Heap()
const maps = [userId, ...followeeId]
for(let i = 0; i < maps.length; i++) {
const curFollowee = this.users[maps[i]]
if (curFollowee) {
const followeeHeapData = curFollowee.heap
for (let j = 0; j < followeeHeapData.length; j++) {
showHeap.push(followeeHeapData[j])
if (showHeap.size() > this.max) {
showHeap.pop()
}
}
}
}
const res = []
for (let i = 0; i < this.max && showHeap.size(); i++) {
res.push(showHeap.top().tweetId)
showHeap.pop()
}
return res.reverse()
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.follow = function(followerId, followeeId) {
if (!this.users[followerId]) {
this.users[followerId] = { heap: [], followeeId: [] }
}
if (this.users[followerId].followeeId.indexOf(followeeId) > -1) return
this.users[followerId].followeeId.push(followeeId)
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.unfollow = function(followerId, followeeId) {
this.users[followerId].followeeId = this.users[followerId].followeeId.filter(v => v !== followeeId)
}
解析
- 发布的时候,按照发布的userId 把tweetId 存起来, 因为优势时间上的先手顺序 搞个下标 每次任何一个发布都加1
- 关联的时候把关联的id给存在userId里
- 推送的时候 也就是输出的时候,用按照时间顺序的小顶堆保持10条 输出就可以了
- 主要还是用优先队列封装的应用