gpt4 book ai didi

java - 检查Java列表中是否有连续点大于阈值

转载 作者:行者123 更新时间:2023-12-04 17:25:45 24 4
gpt4 key购买 nike

我有一个列表 List<Double>表示从服务器指标收集的延迟值。我想检查是否有 3 个连续值大于给定阈值。

例如阈值 = 20

列表 1:[15.121, 15.245, 20.883, 20.993, 15.378, 15.447, 15.839, 15.023]应该返回 false,因为只有两个值 20.883, 20.993大于 20。

list 2:[15.121, 15.245, 20.883, 20.993, 15.378, 15.447, 20.193, 15.023]应该返回 false,因为只有三个大于 20 的值,但它们不是连续的。

列表 3:[15.121, 15.245, 20.883, 20.993, 20.193, 15.378, 15.447, 15.023]应该返回 true,因为有三个连续的值 20.883, 20.993, 20.193大于 20。

我可以使用索引循环来检查 list.get(i-1)、list.get(i) 和 list.get(i+1)。

public boolean isAboveThreshold(List<Double> list, Double threshold) {
// CONSECUTIVE_NUMBER = 3
if (list.size() < CONSECUTIVE_NUMBER) {
return false;
}

return !IntStream.range(0, list.size() - 2)
.filter(i -> list.get(i) > threshold && list.get(i + 1) > threshold && list.get(i + 2) > thread)
.collect(Collectors.toList())
.isEmpty();
}

只是想知道有没有更有效的方法来做到这一点?

更新为 anyMatch基于 Andy Turner的评论。
public boolean isAboveThreshold(List<Double> values, Double threshold, int consecutiveNumber) {
if (values.size() < consecutiveNumber) {
return false;
}

return IntStream
.range(0, values.size() - consecutiveNumber + 1)
.anyMatch(index ->
IntStream.range(index, index + consecutiveNumber)
.allMatch(i -> values.get(i) > threshold)
);
}

最佳答案

最简单的方法是使用增强的 for 循环来完成,计算您在连续运行中看到的元素数量:

int count = 0;
for (double d : list) {
if (d >= threshold) {
// Increment the counter, value was big enough.
++count;
if (count >= 3) {
return true;
}
} else {
// Reset the counter, value too small.
count = 0;
}
}
return false;

关于java - 检查Java列表中是否有连续点大于阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60459465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com