题目地址:
https://www.lintcode.com/problem/pub-sub-pattern/description
要求实现一个发布/订阅模式。实现下面功能:
1、subscribe(channel, user_id)
:将给定用户订阅到给定频道。
2、unsubscribe(channel, user_id)
:取消订阅给定用户的给定用户。
3、publish(channel, message)
:您需要将消息发布到频道,以便在频道上订阅的每个人都会收到此消息。 调用PushNotification.notify(user_id, message)
将消息推送给用户。
思路是哈希表,key是channel名,value是个HashSet,存订阅这个channel的user_id。代码如下:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PubSubPattern {
private Map<String, Set<Integer>> map;
public PubSubPattern() {
// Write your code here
map = new HashMap<>();
}
/**
* @param channel: the channel's name
* @param user_id: the user who subscribes the channel
* @return: nothing
*/
public void subscribe(String channel, int user_id) {
// Write your code here
map.putIfAbsent(channel, new HashSet<>());
map.get(channel).add(user_id);
}
/**
* @param channel: the channel's name
* @param user_id: the user who unsubscribes the channel
* @return: nothing
*/
public void unsubscribe(String channel, int user_id) {
// Write your code here
Set<Integer> set = map.get(channel);
if (set != null && !set.isEmpty()) {
set.remove(user_id);
}
}
/**
* @param channel: the channel's name
* @param message: the message need to be delivered to the channel's subscribers
* @return: nothing
*/
public void publish(String channel, String message) {
// Write your code here
Set<Integer> set = map.get(channel);
if (set != null && !set.isEmpty()) {
for (int user_id : set) {
PushNotification.notify(user_id, message);
}
}
}
}
class PushNotification {
public static void notify(int user_id, String the_message) {}
}
所有操作时间复杂度 O ( 1 ) O(1) O(1),空间与具体所有频道共多少人订阅有关。