123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- type Twitter struct {
- tweets map[int]*list.List
- follow map[int]map[int]bool
- ts int
- }
- type tweet struct {
- id int
- ts int
- }
- type tweetPQ []*list.Element
- func (pq tweetPQ) Len() int { return len(pq) }
- 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.(*list.Element))
- }
- func (pq *tweetPQ) Pop() interface{} {
- x := (*pq)[pq.Len()-1]
- *pq = (*pq)[:pq.Len()-1]
- return x
- }
- /** 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
- }
- /** Compose a new tweet. */
- 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
- }
- this.ts++
- }
- /** 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 {
- feed := make([]int, 0)
- if user, ok := this.follow[userId]; ok {
- var pq tweetPQ
- for uid, _ := range user {
- if li, ok := this.tweets[uid]; ok {
- 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)
- }
- }
- }
- return feed
- }
- /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
- func (this *Twitter) Follow(followerId int, followeeId int) {
- if user, ok := this.follow[followerId]; !ok {
- this.follow[followerId] = map[int]bool{followerId: true, followeeId: true}
- } else {
- user[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 user, ok := this.follow[followerId]; ok && followerId != followeeId {
- delete(user, followeeId)
- }
- }
- /**
- * 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);
- */
|