有两个用例过不了,好忧伤啊~
public static void main(String[] args) {
//["Twitter","postTweet","postTweet","postTweet","postTweet","postTweet","postTweet","postTweet","postTweet","postTweet","postTweet","getNewsFeed","follow","getNewsFeed"]
//[[],[2,5],[1,3],[1,101],[2,13],[2,10],[1,2],[2,94],[2,505],[1,333],[1,22],[2],[2,1],[2]]
Twitter twitter = new Twitter();
twitter.postTweet(2,5);
twitter.postTweet(1,3);
twitter.postTweet(1,101);
twitter.postTweet(2,13);
twitter.postTweet(2,10);
twitter.postTweet(1,2);
twitter.postTweet(2,94);
twitter.postTweet(2,505);
twitter.postTweet(1,333);
twitter.postTweet(1,22);
twitter.getNewsFeed(2);
twitter.follow(2,1);
twitter.getNewsFeed(2);
}
private int count = 0;
class Node{
private long time;
private int messageId;
public Node(long time, int messageId) {
this.time = time;
this.messageId = messageId;
}
}
private Map<Integer, Set<Integer>> followeeIds;
private Map<Integer, List<Node>> news;
public Twitter() {
followeeIds = new HashMap<>();
news = new HashMap<>();
}
/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
Node n = new Node(count++,tweetId);
List<Node> myNew = news.getOrDefault(userId,new ArrayList<>());
myNew.add(n);
news.put(userId, myNew);
}
/** 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. */
public List<Integer> getNewsFeed(int userId) {
List<Node> myNew ;
if(news.get(userId)==null||news.get(userId).isEmpty()){
myNew = new ArrayList<>();
} else {
myNew = new ArrayList<>(news.get(userId));
}
Set<Integer> followees = followeeIds.get(userId);
if(followees!=null){
for(Integer f: followees) {
List<Node> otherNew = news.get(f);
if(otherNew!=null)
myNew.addAll(otherNew);
}
}
Collections.sort(myNew, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o2.time-o1.time>0?1:-1;
}
});
List<Integer> res = new ArrayList<>();
for(int i = 0; i < 10&&i<myNew.size(); i++) {
if(!res.contains(myNew.get(i).messageId))
res.add(myNew.get(i).messageId);
}
return res;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
public void follow(int followerId, int followeeId) {
Set<Integer> follewees = followeeIds.getOrDefault(followerId, new HashSet<>());
follewees.add(followeeId);
followeeIds.put(followerId, follewees);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
public void unfollow(int followerId, int followeeId) {
Set<Integer> follewees = followeeIds.get(followerId);
follewees.remove(followeeId);
followeeIds.put(followerId, follewees);
}
网友评论