Ai
1 Star 0 Fork 0

catyMap/AlgorithmNote

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Twitter.go 2.58 KB
一键复制 编辑 原始数据 按行查看 历史
catyMap 提交于 2021-05-20 08:59 +08:00 . 添加一些堆和有限队列的问题
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);
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

搜索帮助