You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
2.1 KiB
Java
61 lines
2.1 KiB
Java
import java.util.*;
|
|
|
|
public class LogAnalyzerService {
|
|
|
|
// 方法:分析日志并回答查询
|
|
public List<Integer> analyzeLogs(int[][] logData, int x, int[] queries) {
|
|
// 用于记录每个服务器最后一次请求的时间
|
|
Map<Integer, Integer> lastRequestTime = new HashMap<>();
|
|
|
|
// 遍历日志数据,更新每个服务器的最后一次请求时间
|
|
for (int[] logEntry : logData) {
|
|
int serverId = logEntry[0];
|
|
int time = logEntry[1];
|
|
lastRequestTime.put(serverId, Math.max(lastRequestTime.getOrDefault(serverId, 0), time));
|
|
}
|
|
|
|
// 存储查询结果的列表
|
|
List<Integer> results = new ArrayList<>();
|
|
|
|
// 遍历每个查询
|
|
for (int queryTime : queries) {
|
|
int startTime = queryTime - x;
|
|
int inactiveServersCount = 0;
|
|
|
|
// 检查每个服务器在查询的时间区间内是否有请求
|
|
for (int serverId = 1; serverId <= lastRequestTime.size(); serverId++) {
|
|
if (!lastRequestTime.containsKey(serverId) || lastRequestTime.get(serverId) < startTime) {
|
|
// 服务器不存在或最后请求时间在查询区间之前,视为不活跃
|
|
inactiveServersCount++;
|
|
}
|
|
}
|
|
|
|
// 将不活跃服务器的数量添加到结果列表中
|
|
results.add(inactiveServersCount);
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
// 示例日志数据
|
|
int[][] logData = {
|
|
{1, 1},
|
|
{2, 3},
|
|
{3, 5},
|
|
{1, 6},
|
|
{2, 8}
|
|
};
|
|
|
|
int x = 2; // 时间窗口
|
|
int[] queries = {5, 7, 9}; // 查询时间点
|
|
|
|
LogAnalyzerService service = new LogAnalyzerService();
|
|
List<Integer> results = service.analyzeLogs(logData, x, queries);
|
|
|
|
// 输出查询结果
|
|
for (int i = 0; i < queries.length; i++) {
|
|
System.out.println("For query at time " + queries[i] + ", number of inactive servers: " + results.get(i));
|
|
}
|
|
}
|
|
} |