【Lintcode】560. Friendship Service

题目地址:

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),得到列表的时间复杂度取决于列表多长。空间复杂度取决于各个人的关注和被关注列表多长。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值