Compare Intervals (JodaTime) in a list for overlap(比较列表中的间隔 (JodaTime) 是否有重叠)
问题描述
我有一个区间列表,我需要比较它们是否有重叠.
I have a list of intervals, and I need to compare them for overlaps.
List<Interval> intervals = new ArrayList<>();
intervals.add(new Interval(dateTime1, dateTime2));
intervals.add(new Interval(dateTime3, dateTime4));
intervals.add(new Interval(dateTime5, dateTime6));
例如.日期时间1 = 2014-06-01日期时间2 = 2014-07-01
eg. dateTime1 = 2014-06-01 dateTime2 = 2014-07-01
日期时间3 = 2014-08-01dateTime4 = 2014-09-01
dateTime3 = 2014-08-01 dateTime4 = 2014-09-01
日期时间5 = 2014-08-15dateTime6 = 2014-09-15
dateTime5 = 2014-08-15 dateTime6 = 2014-09-15
在这种情况下,第二个和第三个间隔之间存在重叠.我可以使用 Interval.overlaps 方法来找到它.我正在考虑 2 个 for 循环并遍历列表中的每个间隔进行比较.但该解决方案是 O(n*n).有什么更有效的方法来做到这一点?
In this case, there is an overlap between the 2nd and the 3rd interval. I can use the Interval.overlaps method to find that. I'm thinking of 2 for loops and going through each of the intervals in the list to compare. But that solution is O(n*n). What is a more efficient way to do this?
推荐答案
你应该先按开始时间排序升序,然后只应用一个for循环 找出哪些区间是重叠的.
You should first sort the intervals by start time in ascending order and then apply only one for-loop to find out which intervals are overlapping.
使用单个 for 循环解决方案时,您需要比较两个相邻间隔是否重叠.当然,您还必须检查循环的范围条件,以注意每次循环运行时考虑两个间隔.像这样的东西(未测试):
When using the single for-loop-solution you need to compare TWO neighbour intervals if they overlap or not. Of course you have to check the range condition of the loop, too, to pay attention for that you consider two intervals per single loop run. Something like this (not tested):
public boolean isOverlapping(List<Interval> sortedIntervals) {
for (int i = 0, n = sortedIntervals.size(); i < n - 1; i++) {
if (sortedIntervals.get(i).overlaps(sortedIntervals.get(i + 1))) {
return true; // your evaluation for overlap case
}
}
return false;
}
这篇关于比较列表中的间隔 (JodaTime) 是否有重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较列表中的间隔 (JodaTime) 是否有重叠


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01