|
@@ -9,14 +9,14 @@ type tweet struct {
|
|
|
ts int
|
|
|
}
|
|
|
|
|
|
-type tweetPQ []tweet
|
|
|
+type tweetPQ []*list.Element
|
|
|
|
|
|
func (pq tweetPQ) Len() int { return len(pq) }
|
|
|
-func (pq tweetPQ) Less(i, j int) bool { return pq[j].ts < pq[i].ts }
|
|
|
+func (pq tweetPQ) Less(i, j int) bool { return pq[j].Value.(tweet).ts < pq[i].Value.(tweet).ts }
|
|
|
func (pq tweetPQ) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] }
|
|
|
|
|
|
func (pq *tweetPQ) Push(x interface{}) {
|
|
|
- *pq = append(*pq, x.(tweet))
|
|
|
+ *pq = append(*pq, x.(*list.Element))
|
|
|
}
|
|
|
|
|
|
func (pq *tweetPQ) Pop() interface{} {
|
|
@@ -27,6 +27,7 @@ func (pq *tweetPQ) Pop() interface{} {
|
|
|
|
|
|
/** Initialize your data structure here. */
|
|
|
func Constructor() (twitter Twitter) {
|
|
|
+ twitter.tweets = make(map[int]*list.List)
|
|
|
twitter.follow = make(map[int]map[int]bool)
|
|
|
return
|
|
|
}
|
|
@@ -36,6 +37,9 @@ func (this *Twitter) PostTweet(userId int, tweetId int) {
|
|
|
if li, ok := this.tweets[userId]; ok {
|
|
|
li.PushFront(tweet{tweetId, this.ts})
|
|
|
} else {
|
|
|
+ if _, ok := this.follow[userId]; !ok {
|
|
|
+ this.follow[userId] = map[int]bool{userId: true}
|
|
|
+ }
|
|
|
li = list.New()
|
|
|
li.PushFront(tweet{tweetId, this.ts})
|
|
|
this.tweets[userId] = li
|
|
@@ -50,7 +54,18 @@ func (this *Twitter) GetNewsFeed(userId int) []int {
|
|
|
var pq tweetPQ
|
|
|
for uid, _ := range user {
|
|
|
if li, ok := this.tweets[uid]; ok {
|
|
|
- heap.Push(&pq, li.Front().Value.(tweet))
|
|
|
+ heap.Push(&pq, li.Front())
|
|
|
+ }
|
|
|
+ }
|
|
|
+ for pq.Len() != 0 {
|
|
|
+ t := heap.Pop(&pq).(*list.Element)
|
|
|
+ feed = append(feed, t.Value.(tweet).id)
|
|
|
+ if len(feed) == 10 {
|
|
|
+ return feed
|
|
|
+ }
|
|
|
+ t = t.Next()
|
|
|
+ if t != nil {
|
|
|
+ heap.Push(&pq, t)
|
|
|
}
|
|
|
}
|
|
|
}
|
|
@@ -68,7 +83,7 @@ func (this *Twitter) Follow(followerId int, followeeId int) {
|
|
|
|
|
|
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
|
|
|
func (this *Twitter) Unfollow(followerId int, followeeId int) {
|
|
|
- if user, ok := this.follow[followerId]; ok {
|
|
|
+ if user, ok := this.follow[followerId]; ok && followerId != followeeId {
|
|
|
delete(user, followeeId)
|
|
|
}
|
|
|
}
|