355.design-twitter.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. type Twitter struct {
  2. tweets map[int]*list.List
  3. follow map[int]map[int]bool
  4. ts int
  5. }
  6. type tweet struct {
  7. id int
  8. ts int
  9. }
  10. type tweetPQ []tweet
  11. func (pq tweetPQ) Len() int { return len(pq) }
  12. func (pq tweetPQ) Less(i, j int) bool { return pq[j].ts < pq[i].ts }
  13. func (pq tweetPQ) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] }
  14. func (pq *tweetPQ) Push(x interface{}) {
  15. *pq = append(*pq, x.(tweet))
  16. }
  17. func (pq *tweetPQ) Pop() interface{} {
  18. x := (*pq)[pq.Len()-1]
  19. *pq = (*pq)[:pq.Len()-1]
  20. return x
  21. }
  22. /** Initialize your data structure here. */
  23. func Constructor() (twitter Twitter) {
  24. twitter.follow = make(map[int]map[int]bool)
  25. return
  26. }
  27. /** Compose a new tweet. */
  28. func (this *Twitter) PostTweet(userId int, tweetId int) {
  29. if li, ok := this.tweets[userId]; ok {
  30. li.PushFront(tweet{tweetId, this.ts})
  31. } else {
  32. li = list.New()
  33. li.PushFront(tweet{tweetId, this.ts})
  34. this.tweets[userId] = li
  35. }
  36. this.ts++
  37. }
  38. /** 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. */
  39. func (this *Twitter) GetNewsFeed(userId int) []int {
  40. feed := make([]int, 0)
  41. if user, ok := this.follow[userId]; ok {
  42. var pq tweetPQ
  43. for uid, _ := range user {
  44. if li, ok := this.tweets[uid]; ok {
  45. heap.Push(&pq, li.Front().Value.(tweet))
  46. }
  47. }
  48. }
  49. return feed
  50. }
  51. /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
  52. func (this *Twitter) Follow(followerId int, followeeId int) {
  53. if user, ok := this.follow[followerId]; !ok {
  54. this.follow[followerId] = map[int]bool{followerId: true, followeeId: true}
  55. } else {
  56. user[followeeId] = true
  57. }
  58. }
  59. /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
  60. func (this *Twitter) Unfollow(followerId int, followeeId int) {
  61. if user, ok := this.follow[followerId]; ok {
  62. delete(user, followeeId)
  63. }
  64. }
  65. /**
  66. * Your Twitter object will be instantiated and called as such:
  67. * obj := Constructor();
  68. * obj.PostTweet(userId,tweetId);
  69. * param_2 := obj.GetNewsFeed(userId);
  70. * obj.Follow(followerId,followeeId);
  71. * obj.Unfollow(followerId,followeeId);
  72. */