Skip to content

Commit ae9db65

Browse files
Create 0355-design-twitter.go
Accepted submission: _https://leetcode.com/submissions/detail/870783670/_
1 parent 357dba2 commit ae9db65

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

go/0355-design-twitter.go

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
type Tweet struct {
2+
count int
3+
tweetId int
4+
followeeId int
5+
index int
6+
}
7+
8+
type TweetHeap []*Tweet
9+
func (h TweetHeap) Len() int { return len(h) }
10+
func (h TweetHeap) Less(i, j int) bool { return h[i].count < h[j].count }
11+
func (h TweetHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
12+
func (h *TweetHeap) Push(x interface{}) {*h = append(*h, x.(*Tweet))}
13+
func (h *TweetHeap) Pop() interface{} {
14+
old := *h
15+
n := len(old)
16+
x := old[n-1]
17+
*h = old[0 : n-1]
18+
return x
19+
}
20+
21+
type Twitter struct {
22+
count int
23+
tweetMap map[int][]*Tweet
24+
followMap map[int]map[int]bool
25+
}
26+
27+
func Constructor() Twitter {
28+
return Twitter{tweetMap: make(map[int][]*Tweet), followMap: make(map[int]map[int]bool)}
29+
}
30+
31+
func (this *Twitter) PostTweet(userId int, tweetId int) {
32+
if _, ok := this.tweetMap[userId]; !ok {
33+
this.tweetMap[userId] = make([]*Tweet, 0)
34+
}
35+
this.tweetMap[userId] = append(this.tweetMap[userId], &Tweet{count: this.count, tweetId: tweetId})
36+
this.count -= 1
37+
}
38+
39+
40+
func (this *Twitter) GetNewsFeed(userId int) []int {
41+
res := make([]int, 0)
42+
minHeap := TweetHeap{}
43+
44+
if _, ok := this.followMap[userId]; !ok {
45+
this.followMap[userId] = make(map[int]bool)
46+
}
47+
this.followMap[userId][userId] = true;
48+
for followeeId, _ := range this.followMap[userId] {
49+
if _, ok := this.tweetMap[followeeId]; ok {
50+
index := len(this.tweetMap[followeeId]) - 1
51+
tweet := this.tweetMap[followeeId][index]
52+
heap.Push(&minHeap, &Tweet{
53+
count: tweet.count,
54+
tweetId: tweet.tweetId,
55+
followeeId: followeeId,
56+
index: index - 1})
57+
}
58+
}
59+
60+
for len(minHeap) > 0 && len(res) < 10 {
61+
tweet := heap.Pop(&minHeap).(*Tweet)
62+
res = append(res, tweet.tweetId)
63+
if tweet.index >= 0 {
64+
nextTweet := this.tweetMap[tweet.followeeId][tweet.index]
65+
heap.Push(&minHeap, &Tweet{count: nextTweet.count,
66+
tweetId: nextTweet.tweetId,
67+
followeeId: tweet.followeeId,
68+
index: tweet.index - 1})
69+
}
70+
}
71+
return res
72+
}
73+
74+
75+
func (this *Twitter) Follow(followerId int, followeeId int) {
76+
if _, ok := this.followMap[followerId]; !ok {
77+
this.followMap[followerId] = make(map[int]bool)
78+
}
79+
this.followMap[followerId][followeeId] = true
80+
}
81+
82+
83+
func (this *Twitter) Unfollow(followerId int, followeeId int) {
84+
if _, ok := this.followMap[followerId]; ok {
85+
delete(this.followMap[followerId], followeeId)
86+
}
87+
}

0 commit comments

Comments
 (0)