//先定义一个数据结构,代表一条微博,有两个内容:发布者id,微博id(代表微博内容) class TwitterData { int userId; int twitterId; public TwitterData(int userId,int twitterId) { this.twitterId = twitterId; this.userId = userId; } } //用一个map存储用户和各用户的关注用户 Map<Integer,Set<Integer>> userManager ; //用一个linkedList来存储所有微博 List<TwitterData> twitterDatas ; /** Initialize your data structure here. */ public Twitter() { userManager = new HashMap<>(); twitterDatas= new LinkedList<>(); } /** Compose a new tweet. */ public void postTweet(int userId, int tweetId) { //用户名如果没有注册,那就自动注册 if (!userManager.containsKey(userId)) { Set<Integer> follows = new HashSet<>(); //这里注意,要想看到自己的微博,也要关注自己 follows.add(userId); userManager.put(userId,follows); } TwitterData t = new TwitterData(userId,tweetId); //添加到微博列表,每次都是添加到头部,代表是新的 twitterDatas.add(0,t); } /** 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. */ //这里的意思是显示userId关注的人的前10条微博,而不是userId的微博 public List<Integer> getNewsFeed(int userId) { List<Integer> res = new ArrayList<>(); //用户如果不存在,那么就不显示 if (userManager.containsKey(userId)) { Set<Integer> follows = userManager.get(userId); //计数,只显示10条 int count = 0; for (TwitterData t: twitterDatas) { if (count==10) break; //只添加关注用户的微博 if (follows.contains(t.userId)) { res.add(t.twitterId); count++; } } } return res; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ public void follow(int followerId, int followeeId) { //er是主动方,ee是被动方 //考虑两个用户不存在的情况 Set<Integer> follows; if (!userManager.containsKey(followerId)) { follows = new HashSet<>(); follows.add(followerId); userManager.put(followerId,follows); } if (!userManager.containsKey(followeeId)) { follows = new HashSet<>(); follows.add(followeeId); userManager.put(followeeId,follows); } //两者都存在后 follows = userManager.get(followerId); follows.add(followeeId); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ public void unfollow(int followerId, int followeeId) { //排除各种情况后删除就行 if (followerId!=followeeId&&userManager.containsKey(followerId)&&userManager.containsKey(followeeId)) userManager.get(followerId).remove(followeeId); }