代码拉取完成,页面将自动刷新
package main
import "sort"
type User struct {
Id int
Focus map[int]bool
Twis []Twi
}
type Twi struct {
sortId int
TwiId int
}
type Twitter struct {
TwisCount int
UsersTable map[int]*User
}
/** Initialize your data structure here. */
func Constructor() Twitter {
return Twitter{
0,
make(map[int]*User),
}
}
/** Compose a new tweet. */
func (this *Twitter) PostTweet(userId int, tweetId int) {
// 用户首次发推,自动给用户注册
if _ , ok := this.UsersTable[userId] ; !ok {
this.UsersTable[userId] = &User{
Id: userId,
Focus: make(map[int]bool),
Twis: make([]Twi, 0, 0),
}
}
u := this.UsersTable[userId]
u.Twis = append(u.Twis, Twi{this.TwisCount,tweetId} )
this.TwisCount ++
}
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
func (this *Twitter) GetNewsFeed(userId int) []int {
u, ok := this.UsersTable[userId]
if !ok {
return []int{}
}
res := make([]Twi, 0, 0)
res = append(res, u.Twis...)
for id , ok1 := range u.Focus {
fu, ok2 := this.UsersTable[id]
if ok1 && ok2 {
res = append(res, fu.Twis...)
}
}
sort.Slice(res, func(i, j int) bool {
return res[i].sortId > res[j].sortId
})
messages := make([]int, 0,0)
for i := 0 ; i < min(len(res), 10) ; i ++ {
messages = append(messages, res[i].TwiId)
}
return messages
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
func (this *Twitter) Follow(followerId int, followeeId int) {
if _ , ok := this.UsersTable[followerId] ; !ok {
this.UsersTable[followerId] = &User{
Id: followerId,
Focus: make(map[int]bool),
Twis: make([]Twi,0 ,0),
}
}
_ , hasFollow := this.UsersTable[followerId].Focus[followeeId]
if !hasFollow {
this.UsersTable[followerId].Focus[followeeId] = true
}
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
func (this *Twitter) Unfollow(followerId int, followeeId int) {
if _, ok := this.UsersTable[followerId] ; !ok {
return
}
// 必须是已经关注过的
if _ , ok := this.UsersTable[followerId].Focus[followeeId] ; ok {
delete(this.UsersTable[followerId].Focus, followeeId)
}
}
func min(a, b int) int {
if a < b{
return a
}
return b
}
/**
* Your Twitter object will be instantiated and called as such:
* obj := Constructor();
* obj.PostTweet(userId,tweetId);
* param_2 := obj.GetNewsFeed(userId);
* obj.Follow(followerId,followeeId);
* obj.Unfollow(followerId,followeeId);
*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。