Code to find all merging intervals
This is a code to find all overlaps in intervals. Example: [0-20] [15-40]
[25 -50] are 3 intervals then the output should be : (15-20), (25-40). I
could not find and answer with complexity lesser than O(n2). Please let me
know a better solutions if it exists. Additionally assume input is sorted
by starttime.
public static Set<OverlapCoord> getOverlap(List<Interval> intervalList) {
if (intervalList == null) {
throw new NullPointerException("Input list cannot be null.");
}
final HashSet<OverlapCoord> hashSet = new HashSet<OverlapCoord>();
for (int i = 0; i < intervalList.size() - 1; i++) {
final Interval intervali = intervalList.get(i);
for (int j = 0; j < intervalList.size(); j++) {
final Interval intervalj = intervalList.get(j);
if (intervalj.getStart() < intervali.getEnd() &&
intervalj.getEnd() > intervali.getStart() && i != j) {
hashSet.add(new
OverlapCoord(Math.max(intervali.getStart(),intervalj.getStart()),
Math.min(intervali.getEnd(),
intervalj.getEnd())));
}
}
}
return hashSet;
}
No comments:
Post a Comment