dengxinyi 6 年之前
父节点
当前提交
121dcb74b3
共有 1 个文件被更改,包括 84 次插入0 次删除
  1. 84 0
      medium/355.design-twitter.go

+ 84 - 0
medium/355.design-twitter.go

@@ -0,0 +1,84 @@
+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 []tweet
+
+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) Swap(i, j int)      { pq[i], pq[j] = pq[j], pq[i] }
+
+func (pq *tweetPQ) Push(x interface{}) {
+	*pq = append(*pq, x.(tweet))
+}
+
+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.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 {
+		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().Value.(tweet))
+			}
+		}
+	}
+	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 {
+		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);
+ */
+