中等
技术面试0 次浏览

微博的用户可以关注其他用户,形成关注关系。请设计一个系统来管理用户的关注关系,并实现以下功能:添加关注、取消关注和查询某个用户的所有关注用户。

微博测试工程师
系统设计关注关系管理数据结构

答题要点

推荐使用分层分析法,从数据结构设计、功能实现和接口设计三个层面来答题。关键要点如下:1. 选择合适的数据结构,如字典来存储用户的关注关系。2. 实现添加关注、取消关注和查询关注用户的功能。3. 设计清晰的接口,方便调用这些功能。示例思路:使用一个字典`follow_relations`来存储用户的关注关系,键为用户ID,值为该用户关注的用户ID列表。实现`add_follow`、`remove_follow`和`get_followed_users`三个函数来完成相应的功能。示例代码如下:python follow_relations = {} def add_follow(user_id, followed_id): if user_id not in follow_relations: follow_relations[user_id] = [] if followed_id not in follow_relations[user_id]: follow_relations[user_id].append(followed_id) def remove_follow(user_id, followed_id): if user_id in follow_relations and followed_id in follow_relations[user_id]: follow_relations[user_id].remove(followed_id) def get_followed_users(user_id): return follow_relations.get(user_id, [])