题目地址:
https://www.lintcode.com/problem/friendship-service/description
要求实现一个朋友之间的关注和取关系统,要求实现下面功能:
1、获得某个id的人的关注列表和被关注列表(关注列表即他关注了谁,被关注列表即谁关注了他),要求返回列表的时候列表按照id排序;
2、给定两个id,实现第一个id的人关注第二个id的人的功能。
思路是用两个哈希表,一个存关注列表,key是id,value是一个TreeSet,存的是这个id关注了哪些id;另一个存被关注列表,key和value类似。代码如下:
import java.util.*;
public class FriendshipService {
private Map<Integer, Set<Integer>> followers, followings;
public FriendshipService() {
// do intialization if necessary
followers = new HashMap<>();
followings = new HashMap<>();
}
/*
* @param user_id: An integer
* @return: all followers and sort by user_id
*/
public List<Integer> getFollowers(int user_id) {
// write your code here
return followers.containsKey(user_id) ? new ArrayList<>(followers.get(user_id)) : new ArrayList<>();
}
/*
* @param user_id: An integer
* @return: all followings and sort by user_id
*/
public List<Integer> getFollowings(int user_id) {
// write your code here
return followings.containsKey(user_id) ? new ArrayList<>(followings.get(user_id)) : new ArrayList<>();
}
/*
* @param from_user_id: An integer
* @param to_user_id: An integer
* @return: nothing
*/
public void follow(int to_user_id, int from_user_id) {
// write your code here
followers.putIfAbsent(to_user_id, new TreeSet<>());
followers.get(to_user_id).add(from_user_id);
followings.putIfAbsent(from_user_id, new TreeSet<>());
followings.get(from_user_id).add(to_user_id);
}
/*
* @param from_user_id: An integer
* @param to_user_id: An integer
* @return: nothing
*/
public void unfollow(int to_user_id, int from_user_id) {
// write your code here
if (followers.containsKey(to_user_id)) {
followers.get(to_user_id).remove(from_user_id);
}
if (followings.containsKey(from_user_id)) {
followings.get(from_user_id).remove(to_user_id);
}
}
}
关注和取关时间复杂度 O ( 1 ) O(1) O(1),得到列表的时间复杂度取决于列表多长。空间复杂度取决于各个人的关注和被关注列表多长。