【发布时间】:2019-06-24 16:46:18
【问题描述】:
我有两个列表,每组间隔。我想找到两个列表的交集。
Eg.
List1 = [{1, 10}, {15, 25}, {30, 32}];
List2 = [{3,5}, {9,14}, {17,20}];
结果:
IntersectionList = [{3,5}, {9,10}, {17,20}];
我尝试过使用: Java algorithm for find intersection between intervals 但这在第一个列表中只有一个对象。
我希望能够在每个列表中提供多个区间对象。
public class CalendarTimeSlot {
private long from;
private long to;
}
public class IntersectIntervalsHelper {
public static void main(String[] args) {
List<CalendarTimeSlot> l1 = new ArrayList<>();
l1.add(new CalendarTimeSlot(1, 10));
l1.add(new CalendarTimeSlot(15, 25));
l1.add(new CalendarTimeSlot(30, 32));
List<CalendarTimeSlot> l2 = new ArrayList<>();
l2.add(new CalendarTimeSlot(3, 5));
l2.add(new CalendarTimeSlot(9, 14));
l2.add(new CalendarTimeSlot(17, 20));
//todo code here to do l1 intersection l2 slots
}
}
示例输入:
List1 = [{1, 10}, {15, 25}, {30, 32}];
List2 = [{3,5}, {9,14}, {17,20}];
结果:
IntersectionList = [{3,5}, {9,10}, {17,20}];
【问题讨论】:
-
如果是
{9,20},第二个间隔的结果应该是什么?可以是{9,10}或{15,20} -
两者都必须。 o/p 应包含:[{3,5}, {9,10}, {15,20}];
-
为什么预期输出显示 2 个列表?是输入错误吗?
-
你可以用一个BitSet来表示区间,其中每个位索引都是自然数,真/假表示它是否属于区间。然后使用 BitSet.And 方法找到交点。在此之后,以某种方式将结果转储回子间隔列表。
-
提示:到目前为止,您只放弃了要求。如果您想获得更多积极的反馈...考虑自己尝试一些事情。不要指望其他人应该为你做这项工作。