Microsoft 历史查询:某个 agent 在时刻 T 是否健康
在心跳监控基础上,支持查询某个 agent 在过去某个时刻是否处于健康状态。
2025-04OAVO Helper · 面经整理
01 · QUESTIONS
面试题目
- 在心跳监控的基础上,支持查询:某个 agent 在过去某个时刻 T 是否处于健康状态(T 之前 timeout 时间内有过心跳即为健康)。
02 · ANSWERS
参考答案
把每个 agent 相邻间隔不超过 timeout 的心跳合并成「健康区间」[首次心跳, 最后心跳];查询 T 时,二分找到起点不晚于 T 的最后一个区间,判断 T 是否不晚于「该区间最后心跳 + timeout」。
解题思路
- 区间内任意两次心跳间隔都不超过 timeout,所以区间覆盖的每个时刻都是健康的;区间结束后还能健康 timeout 时间。
- 心跳时间单调递增,只需要看最后一个区间:间隔不超过 timeout 就延长,否则新开一个区间。
- 存区间而不是每次心跳,内存从「心跳次数」降到「健康区间数」;再配合保留期限删除过老的数据。
代码
from bisect import bisect_right
from collections import defaultdict
class HealthHistory:
def __init__(self, timeout):
self.timeout = timeout
self.spans = defaultdict(list) # agent -> [[首次心跳, 最后心跳], ...]
def heartbeat(self, agent, ts):
spans = self.spans[agent]
if spans and ts - spans[-1][1] <= self.timeout:
spans[-1][1] = ts # 仍在健康区间内,延长
else:
spans.append([ts, ts])
def was_healthy(self, agent, t):
spans = self.spans.get(agent, [])
i = bisect_right(spans, [t, float('inf')]) - 1 # 起点不晚于 t 的最后一个区间
return i >= 0 and t <= spans[i][1] + self.timeout复杂度
- 心跳:O(1)。
- 查询:O(log m),m 为该 agent 的健康区间数。
- 空间:O(区间数),远小于心跳次数。
联系 OAVO Helper
想针对这题做模拟练习?
加微信 aasummer 咨询陪跑,我们可以按你的目标岗位安排简历、模拟面试或代投。
加微信 aasummer 咨询陪跑微信:aasummer