FriendShip Service

Support follow & unfollow, getFollowers, getFollowings.
Note: the results of getfollow() are sorted.

Example

follow(1, 3)
getFollowers(1) // return [3]
getFollowings(3) // return [1]
follow(2, 3)
getFollowings(3) // return [1,2]
unfollow(1, 3)
getFollowings(3) // return [2]

思路:TreeSet是已经排好序的set,直接用treeset去收集就可以了;

public class FriendshipService {
    private HashMap<Integer, Set<Integer>> followers, followings;
    public FriendshipService() {
        this.followers = new HashMap<Integer, Set<Integer>>();
        this.followings = new HashMap<Integer, Set<Integer>>();
    }

    /*
     * @param user_id: An integer
     * @return: all followers and sort by user_id
     */
    public List<Integer> getFollowers(int user_id) {
        if(!followers.containsKey(user_id)){
            return new ArrayList<Integer>();
        }
        return new ArrayList<Integer>(followers.get(user_id));
    }

    /*
     * @param user_id: An integer
     * @return: all followings and sort by user_id
     */
    public List<Integer> getFollowings(int user_id) {
        if(!followings.containsKey(user_id)) {
            return new ArrayList<Integer>();
        }
        return new ArrayList<Integer>(followings.get(user_id));
    }

    /*
     * @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) {
        if(!followers.containsKey(to_user_id)){
            followers.put(to_user_id, new TreeSet<Integer>());
        }
        followers.get(to_user_id).add(from_user_id);
        
        if(!followings.containsKey(from_user_id)){
            followings.put(from_user_id, new TreeSet<Integer>());
        }
        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) {
        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);
        }
    }
}
发布了569 篇原创文章 · 获赞 13 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104047248