设计一个简化版的推特(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 的用户。
示例:
输入
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
输出
[null, null, [5], null, null, [6, 5], null, [5]]
解释
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // 用户 1 发送了一条新推文 (用户 id = 1, 推文 id = 5)
twitter.getNewsFeed(1); // 用户 1 的获取推文应当返回一个列表,其中包含一个 id 为 5 的推文
twitter.follow(1, 2); // 用户 1 关注了用户 2
twitter.postTweet(2, 6); // 用户 2 发送了一个新推文 (推文 id = 6)
twitter.getNewsFeed(1); // 用户 1 的获取推文应当返回一个列表,其中包含两个推文,id 分别为 -> [6, 5] 。推文 id 6 应当在推文 id 5 之前,因为它是在 5 之后发送的
twitter.unfollow(1, 2); // 用户 1 取消关注了用户 2
twitter.getNewsFeed(1); // 用户 1 获取推文应当返回一个列表,其中包含一个 id 为 5 的推文。因为用户 1 已经不再关注用户 2
分析
这题其实很综合,除了数据结构,还有模型设计相关的东西。
我们维护3个类:
- User类,维护用户ID,用户关注列表,该用的推文信息。
// 用户表
var User = function (userId) {
this.userId = userId;
this.followSet = new Set();
// 链表用来新增消息节点
this.feeds = null;
}
// 消息节点
var LinkNode = function (tweetId, next) {
this.next = next || null;
this.val = {
tweetId,
timestamp: timestamp++
}
}
- 关注列表使用set集合来维护
- 推文信息因为需要最新的推文放在首位,我们可以选择线性数据结构,如数组,链表等,数组头部插入数据需要移动数据,并且还有动态扩容方面需求,所以我们选择链表。
- 堆,因为js没有优先队列,所以我们只能自己实现一个堆。当我们检索最新的10条数据时,除了自身的推文还有关注列表每个人的推文,有点类似多个有序链表合并, 我们使用一个长度为10的小顶堆来维护最新的10条推文。(有个小优化点,当某个关注人的推文时间早于当前堆顶推文,就跳过该关注人的推文。)
// js实现堆
class Heap {
constructor(compare, max) {
this.heap = [];
this.count = 0;
// 默认小顶堆
this.compare = compare || ((a, b) => a < b);
this.max = max || Infinity;
}
}
Heap.prototype.push = function (val) {
if (this.count === this.max) return false;
this.heap[this.count++] = val;
this.heapifyUp();
return true;
}
Heap.prototype.pop = function () {
if (this.count === 0) return false;
const top = this.heap[0];
this.swap(0, this.count - 1);
this.count--;
this.heapifyDown();
return top;
}
Heap.prototype.heapifyDown = function () {
const compare = this.compare;
let i = 0;
while (i < this.count) {
let temp = i;
if (i * 2 + 1 < this.count && compare(this.heap[i * 2 + 1], this.heap[i])) {
temp = i * 2 + 1;
}
if (i * 2 + 2 < this.count && compare(this.heap[i * 2 + 2], this.heap[temp])) {
temp = i * 2 + 2;
}
if (temp === i) break;
this.swap(temp, i);
i = temp;
}
}
Heap.prototype.heapifyUp = function () {
const compare = this.compare;
let i = this.count - 1;
while (i > 0) {
if (compare(this.heap[i], this.heap[(i - 1) >> 1])) {
this.swap(i, (i - 1) >> 1)
i = (i - 1) >> 1
} else {
break;
}
}
}
Heap.prototype.clear = function () {
this.heap = [];
this.count = 0;
}
Heap.prototype.swap = function (a, b) {
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]]
}
Heap.prototype.get = function () {
return this.heap;
}
Heap.prototype.getTop = function () {
return this.heap[0];
}
Heap.prototype.getSize = function () {
return this.count;
}
- Twitter类,用来维护所有用户数据和当前堆信息。
var Twitter = function () {
// 用户表
this.userMap = new Map();
// 小顶堆,用来合并数据
this.maxHeap = new Heap((a, b) => a.timestamp < b.timestamp, MAX_FEEDS);
};
实现
// 因为用Date.now()有可能值相等,在实际情况中应该使用时间戳,这里用自增长的num值代替
let timestamp = 0;
const MAX_FEEDS = 10;
var Twitter = function () {
// 用户表
this.userMap = new Map();
// 小顶堆,用来合并数据
this.maxHeap = new Heap((a, b) => a.timestamp < b.timestamp, MAX_FEEDS);
};
// 用户表
var User = function (userId) {
this.userId = userId;
this.followSet = new Set();
// 链表用来新增消息节点
this.feeds = null;
}
// 消息节点
var LinkNode = function (tweetId, next) {
this.next = next || null;
this.val = {
tweetId,
timestamp: timestamp++
}
}
// 当前用户插入一则新闻
User.prototype.postTweet = function (tweetId) {
const current = this.feeds;
const node = new LinkNode(tweetId, current);
this.feeds = node;
}
// 用户关注
User.prototype.follow = function (followeeId) {
// 关注账号等于当前账号
if (this.userId === followeeId) return;
// 关注列表中有该账号
if (this.followSet.has(followeeId)) return;
this.followSet.add(followeeId);
}
// 用户取关
User.prototype.unfollow = function (followeeId) {
// 关注账号等于当前账号
if (this.userId === followeeId) return;
// 关注列表中无该账号
if (!this.followSet.has(followeeId)) return;
this.followSet.delete(followeeId)
}
/**
* @param {number} userId
* @param {number} tweetId
* @return {void}
*/
Twitter.prototype.postTweet = function (userId, tweetId) {
// 用户表中没有该用户
if (!this.userMap.has(userId)) {
this.userMap.set(userId, new User(userId));
}
const user = this.userMap.get(userId);
user.postTweet(tweetId);
};
/**
* @param {number} userId
* @return {number[]}
*/
Twitter.prototype.getNewsFeed = function (userId) {
if (!this.userMap.has(userId)) return [];
const user = this.userMap.get(userId);
// 使用前先清除堆
this.maxHeap.clear();
// 当前用户有新闻
if (user.feeds) {
let current = user.feeds;
while (current && this.maxHeap.getSize() < MAX_FEEDS) {
this.maxHeap.push(current.val)
current = current.next;
}
}
// 关注列表处理,多路合并
let count = user.followSet.size;
if (count) {
for (let followeeId of user.followSet) {
const curUser = this.userMap.get(followeeId)
let current = curUser.feeds;
while (current) {
// 当前关注用户的后续推文时间都小于堆顶时间,跳过
if (this.maxHeap.getSize() === MAX_FEEDS && current.val.timestamp < this.maxHeap.getTop().timestamp) {
break;
} else {
if (this.maxHeap.getSize() === MAX_FEEDS) {
this.maxHeap.pop();
}
this.maxHeap.push(current.val);
current = current.next;
}
}
}
}
const ans = [];
let heapCount = this.maxHeap.getSize();
// 因为是小顶堆,最上面的时间戳最小,所以要放入结果数组的最尾部
while (heapCount) {
ans.unshift(this.maxHeap.pop().tweetId);
heapCount--;
}
return ans;
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.follow = function (followerId, followeeId) {
// 推特中没有该用户,新建用户
if (!this.userMap.has(followerId)) {
this.userMap.set(followerId, new User(followerId))
}
const user = this.userMap.get(followerId);
// 推特中没有关注用户账号
if (!this.userMap.get(followeeId)) {
this.userMap.set(followeeId, new User(followeeId))
}
user.follow(followeeId);
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.unfollow = function (followerId, followeeId) {
// 推特中没有该用户,新建用户
if (!this.userMap.has(followerId)) {
this.userMap.set(followerId, new User(followerId))
}
const user = this.userMap.get(followerId);
// 推特中没有关注用户账号
if (!this.userMap.get(followeeId)) {
this.userMap.set(followeeId, new User(followeeId))
}
user.unfollow(followeeId);
};
/**
* Your Twitter object will be instantiated and called as such:
* var obj = new Twitter()
* obj.postTweet(userId,tweetId)
* var param_2 = obj.getNewsFeed(userId)
* obj.follow(followerId,followeeId)
* obj.unfollow(followerId,followeeId)
*/