1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| type Twitter struct { userMap map[int]*User }
type User struct { userId int followees map[int]bool tweets []*Tweet }
type Tweet struct { tweetId int time int userId int }
var tweetCount int
func Constructor() Twitter { return Twitter{userMap: make(map[int]*User)} }
func (t *Twitter) PostTweet(userId int, tweetId int) {
if _, ok := t.userMap[userId]; !ok { t.userMap[userId] = &User{userId: userId, tweets: make([]*Tweet, 0), followees: make(map[int]bool)} tweet := &Tweet{tweetId, tweetCount, userId} t.userMap[userId].tweets = append(t.userMap[userId].tweets, tweet) t.userMap[userId].followees[userId] = true } else { tweet := &Tweet{tweetId, tweetCount, userId} t.userMap[userId].tweets = append(t.userMap[userId].tweets, tweet)
}
tweetCount++ }
func (t *Twitter) Follow(followerId int, followeeId int) { if _, ok := t.userMap[followerId]; !ok { t.userMap[followerId] = &User{ userId: followerId, followees: make(map[int]bool), } t.userMap[followerId].followees[followerId] = true }
if _, ok := t.userMap[followeeId]; !ok { t.userMap[followeeId] = &User{ userId: followeeId, followees: make(map[int]bool), } t.userMap[followeeId].followees[followeeId] = true } t.userMap[followerId].followees[followeeId] = true
}
func (t *Twitter) Unfollow(followerId int, followeeId int) { if _, ok := t.userMap[followerId]; ok { delete(t.userMap[followerId].followees, followeeId) } }
func (t *Twitter) GetNewsFeed(userId int) []int { resTop10 := []int{} tweeters := []*Tweet{} if _, ok := t.userMap[userId]; ok {
for followeeId, _ := range t.userMap[userId].followees { tweeters = append(tweeters, t.userMap[followeeId].tweets...) }
} sort.Slice(tweeters, func(i, j int) bool { if tweeters[i].time > tweeters[j].time { return true } return false })
for i := 0; i < len(tweeters) && i < 10 ; i++ { resTop10 = append(resTop10, tweeters[i].tweetId) }
return resTop10 }
|