官方用的动态规划,我用的滑动窗口。
就是维护一个长度为time+1的递减窗口,将符合要求的窗口尾部放入一个set。
然后倒序维护一个长度为time+1的递增窗口,如果符合要求的窗口头部在set中,将其放入答案中。
class Solution {
public List<Integer> goodDaysToRobBank(int[] security, int time) {
Set<Integer> left = new HashSet<>();
int st = 0;
int ed = 0;
while (st != security.length) {
int len = ed - st + 1;
if (len == time + 1) {
left.add(ed);
st++;
}
if (++ed == security.length) {
break;
}
if (security[ed] > security[ed - 1]) {
st = ed;
}
}
List<Integer> ans = new ArrayList<>();
st = security.length - 1;
ed = st;
while (st != -1) {
int len = ed - st + 1;
if (len == time + 1) {
if (left.contains(st)) {
ans.add(st);
}
ed--;
}
if (--st == -1) {
break;
}
if (security[st] > security[st + 1]) {
ed = st;
}
}
return ans;
}
}

这篇博客介绍了一种利用滑动窗口和动态规划算法来解决银行安全警报时间间隔的问题。作者首先建立了一个递减窗口,用于存储在给定时间内没有警报的时间点,并使用HashSet保存这些时间点。接着,通过一个递增窗口从后往前遍历,检查是否存在符合条件的无警报时间段,并将它们添加到答案列表中。这种方法有效地找到了可以抢劫银行而不会触发连续警报的好日子。
9万+

被折叠的 条评论
为什么被折叠?



