首页 > 代码库 > 355. Design Twitter
355. Design Twitter
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:
- postTweet(userId, tweetId): Compose a new tweet.
- getNewsFeed(userId): 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.
- follow(followerId, followeeId): Follower follows a followee.
- 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 posts 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 user 2. twitter.unfollow(1, 2); // User 1‘s news feed should return a list with 1 tweet id -> [5], // since user 1 is no longer following user 2. twitter.getNewsFeed(1);
---------------
自己的方法:
1. 里面包含了三个成员
Map<Integer, List<Integer>> tweets;//map<userId, list<hisTweets>>
Map<Integer, Set<Integer>> relations;//map<follower, list<following>>
Map<String, Integer> tweetsOrder;//map<Key==userId:tweetId, orderInTotal>
tweets里面key是userId,内容是这个用户发的所有tweetId
relations是key是userId,内容是这个用户follow的所有用户
tweetOrder中的key是用户id和tweetId的拼接,value是总编号
2. 在getLastestNews和merge k sorted list差不多,用一个PriorityQueue来维护最近的tweet
还要注意的是get最新10条的时候记得把自己的设置成自己的follower
3. unfollow的时候注意:
1)要检查这个关系是都存在
2)自己不可以unfollow自己
所以代码就是:
1 public class Twitter { 2 Map<Integer, List<Integer>> tweets;//map<userId, list<hisTweets>> 3 Map<Integer, Set<Integer>> relations;//map<follower, list<following>> 4 Map<String, Integer> tweetsOrder;//map<Key==userId:tweetId, orderInTotal> 5 6 /** Initialize your data structure here. */ 7 public Twitter() { 8 tweets = new HashMap<>(); 9 relations = new HashMap<>(); 10 tweetsOrder = new HashMap<>(); 11 } 12 13 /** Compose a new tweet. */ 14 public void postTweet(int userId, int tweetId) { 15 List<Integer> tweetsList = tweets.get(userId); 16 if(tweetsList == null) { 17 tweetsList = new ArrayList<>(); 18 } 19 tweetsList.add(0, tweetId); 20 tweets.put(userId, tweetsList); 21 int index = tweetsOrder.size(); 22 StringBuilder sb = new StringBuilder(); 23 sb.append(userId); 24 sb.append(":"); 25 sb.append(tweetId); 26 tweetsOrder.put(sb.toString(), index); 27 } 28 29 class TweetNode { 30 int userId; 31 int tweetIndex; 32 int tweetId; 33 int tweetOrder; 34 public TweetNode(int userId, int tweetIndex) { 35 this.userId = userId; 36 this.tweetIndex = tweetIndex; 37 this.tweetId = tweets.get(userId).get(tweetIndex); 38 String key = String.valueOf(userId) + ":" + String.valueOf(this.tweetId); 39 this.tweetOrder = tweetsOrder.get(key); 40 } 41 } 42 43 /** 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. */ 44 public List<Integer> getNewsFeed(int userId) { 45 follow(userId, userId); 46 PriorityQueue<TweetNode> pq = new PriorityQueue<>(new Comparator<TweetNode>() { 47 public int compare(TweetNode t1, TweetNode t2) { 48 return t2.tweetOrder - t1.tweetOrder; 49 } 50 }); 51 for(int person: relations.get(userId)) { 52 List<Integer> list = tweets.get(person); 53 if(list != null) { 54 pq.offer(new TweetNode(person, 0)); 55 } 56 } 57 int cnt = 10; 58 List<Integer> res = new ArrayList<>(); 59 while(cnt > 0 && !pq.isEmpty()) { 60 TweetNode cur = pq.poll(); 61 cnt--; 62 res.add(cur.tweetId); 63 if(cur.tweetIndex < tweets.get(cur.userId).size() - 1) { 64 pq.offer(new TweetNode(cur.userId, cur.tweetIndex + 1)); 65 } 66 } 67 return res; 68 } 69 70 /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ 71 public void follow(int followerId, int followeeId) { 72 Set<Integer> following = relations.get(followerId); 73 if(following == null) { 74 following = new HashSet<>(); 75 } 76 following.add(followeeId); 77 relations.put(followerId, following); 78 } 79 80 /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ 81 public void unfollow(int followerId, int followeeId) { 82 Set<Integer> following = relations.get(followerId); 83 if(following != null && followerId != followeeId && following.contains(followeeId)) { 84 following.remove(followeeId); 85 } 86 relations.put(followerId, following); 87 } 88 } 89 90 /** 91 * Your Twitter object will be instantiated and called as such: 92 * Twitter obj = new Twitter(); 93 * obj.postTweet(userId,tweetId); 94 * List<Integer> param_2 = obj.getNewsFeed(userId); 95 * obj.follow(followerId,followeeId); 96 * obj.unfollow(followerId,followeeId); 97 */
————————————————————————————————
ref: https://discuss.leetcode.com/topic/48100/java-oo-design-with-most-efficient-function-getnewsfeed
这个设计得漂亮一些:
1. 把user和tweet都单独建成类
2. 用一个全局static的timestamp来给tweet编上全局的编号,方便排序,在创建一条Tweet的时候更新这个计数
3. 在user类中加入一个Tweet的头,把一个用户的tweets设成一个linkedList,这样可以提高PriorityQueue的工作效率
4. 根据以上的设计,属于Twitter的大类的只有两个成员了,一个是把用户id和User实例对应的map,一个全局的timestamp
1 public class Twitter { 2 private static int timestamp = 0; 3 Map<Integer, User> userMap; 4 5 /** Initialize your data structure here. */ 6 public Twitter() { 7 userMap = new HashMap<>(); 8 } 9 10 class User { 11 int userId; 12 Set<Integer> following; 13 Tweet tweetHead; 14 public User(int userId) { 15 this.userId = userId; 16 following = new HashSet<>(); 17 following.add(userId); 18 tweetHead = null; 19 } 20 21 public void post(int tweetId) { 22 Tweet newTweet = new Tweet(userId, tweetId); 23 newTweet.next = tweetHead; 24 tweetHead = newTweet; 25 } 26 27 public void follow(int followeeId) { 28 following.add(followeeId); 29 } 30 31 public void unfollow(int followeeId) { 32 following.remove(followeeId); 33 } 34 } 35 36 class Tweet { 37 int userId; 38 int tweetId; 39 int time; 40 Tweet next; 41 42 public Tweet(int userId, int tweetId) { 43 this.userId = userId; 44 this.tweetId = tweetId; 45 time = timestamp++; 46 next = null; 47 } 48 } 49 50 51 /** Compose a new tweet. */ 52 public void postTweet(int userId, int tweetId) { 53 User user = userMap.get(userId); 54 if(user == null) { 55 user = new User(userId); 56 userMap.put(userId, user); 57 } 58 user.post(tweetId); 59 } 60 61 /** 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. */ 62 public List<Integer> getNewsFeed(int userId) { 63 List<Integer> res = new ArrayList<>(); 64 if(!userMap.containsKey(userId)) { 65 return res; 66 } 67 PriorityQueue<Tweet> pq = new PriorityQueue<>(new Comparator<Tweet>(){ 68 public int compare(Tweet t1, Tweet t2) { 69 return t2.time - t1.time; 70 } 71 }); 72 for(int id: userMap.get(userId).following) { 73 User curUser = userMap.get(id); 74 if(curUser.tweetHead != null) { 75 pq.offer(curUser.tweetHead); 76 } 77 } 78 int cnt = 10; 79 while(cnt > 0 && !pq.isEmpty()) { 80 Tweet cur = pq.poll(); 81 res.add(cur.tweetId); 82 cnt--; 83 if(cur.next != null) { 84 pq.offer(cur.next); 85 } 86 } 87 return res; 88 } 89 90 /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ 91 public void follow(int followerId, int followeeId) { 92 User follower = userMap.get(followerId); 93 if(follower == null) { 94 follower = new User(followerId); 95 userMap.put(followerId, follower); 96 } 97 User followee = userMap.get(followeeId); 98 if(followee == null) { 99 followee = new User(followeeId); 100 userMap.put(followeeId, followee); 101 } 102 follower.follow(followeeId); 103 } 104 105 /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ 106 public void unfollow(int followerId, int followeeId) { 107 if(userMap.containsKey(followerId) && userMap.containsKey(followeeId) && followerId != followeeId) { 108 userMap.get(followerId).unfollow(followeeId); 109 } 110 } 111 } 112 113 /** 114 * Your Twitter object will be instantiated and called as such: 115 * Twitter obj = new Twitter(); 116 * obj.postTweet(userId,tweetId); 117 * List<Integer> param_2 = obj.getNewsFeed(userId); 118 * obj.follow(followerId,followeeId); 119 * obj.unfollow(followerId,followeeId); 120 */
355. Design Twitter