Topic Connection
Https://leetcode.com/problems/design-twitter
Design twittedescription
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 Most recent tweets in the user s news feed. Your design should support the following methods:
1. Posttweet (userId, Tweetid): Compose a new tweet.
2. getnewsfeed (userId): Retrieve The most recent tweets IDs in the user s news feed. Each item in the news feed must is posted by the users of the user followed or by the user herself. Tweets must is ordered from the most recent to least recent.
3. Follow (Followerid, Followeeid): Follower follows a followee.
4. unfollow (Followerid, Followeeid): Follower unfollows a followee.
Example:
twitter Twitter = new Twitter ()//user 1 posts a new tweet (id = 5). Twitter.posttweet (1, 5);//user 1 ' s News Feed should Return a list with 1 tweet ID, [5].twitter.getnewsfeed (1);//user 1 follows user 2.twitter.follow (1, 2);//USER 2 pos TS a new tweet (id = 6). Twitter.posttweet (2, 6);//User 1 's News Feed should return a list with 2 tweet IDs, [6, 5]./ /Tweet ID 6 should precede tweet ID 5 because it is posted after Tweet ID 5.twitter.getnewsfeed (1);/User 1 unfollows US Er 2.twitter.unfollow (1, 2);//User 1 's News Feed should return a list with 1 tweet ID--[5],//since User 1 is no lon Ger following user 2.twitter.getnewsfeed (1);
According to test instructions direct simulation can be,
I used a fixed-size set to hold 10 most recent IDs.
If the tweets is less than 10 direct inserts, each insert is judged by the last element of the set
(The comparison function has been overloaded, and the elements inside the set are sorted by timestamps from large to small)
PS: Long time has not updated blogs, too lazy (⊙﹏⊙) b
Class Twitter {private:struct P {int id, ref; P (int i = 0, int j = 0): ID (i), ref (j) {} inline bool operator< (const P &a) const {return ref > A.ref;} };p Ublic:twitter () {time = 1;} void Posttweet (int userId, int tweetid) {Userpost[userid].insert (P (Tweetid, time++)); Userfollow[userid].insert (USERID); } vector<int> getnewsfeed (int userId) {q.clear (); vector<int> Res; for (auto &r:userfollow[userid]) {int n = userpost[r].size (); Auto it = Userpost[r].begin (); n = min (n, 10); while (n--) {if (Q.size () <) {Q.insert (*it++); } else {Auto c = q.end (); if (*it < *--c) {q.erase (c); Q.insert (*it++); }}}} for (Auto &r:q) res.push_back (r.id); return res; } void Follow (int followerid, int followeeid) {Userfollow[followerid].insert (Followeeid); } void unfollow (int followerid, int followeeid) {if (Followerid = = Followeeid) return; Userfollow[followerid].erase (Followeeid); }private:int time; Set<p> Q; Unordered_map<int, set<p>> Userpost; Unordered_map<int, set<int>> Userfollow;};
Leetcode 355 Design Twitte