Add a closed interval
InsertInterval.javapublic static List<Interval> insertInterval(List<Interval> intervals,
Interval newInterval) {
int i = 0;
List<Interval> result = new ArrayList<>();
// Inserts intervals appeared before new_interval.
while (i < intervals.size() && newInterval.left > intervals.get(i).right) {
result.add(intervals.get(i++));
}
// Merges intervals that overlap with new_interval.
while (i < intervals.size() && newInterval.right >= intervals.get(i).left) {
newInterval = new Interval(Math.min(newInterval.left,
intervals.get(i).left), Math.max(newInterval.right,
intervals.get(i).right));
++i;
}
result.add(newInterval);
// Inserts intervals appearing after new_interval.
result.addAll(intervals.subList(i, intervals.size()));
return result;
}
Compute the union of intervals
UnionIntervals.javaclass Endpoint {
public boolean isClose;
public int val;
}
public int compareTo(ExInterval i) {
if (left.val < i.left.val) {
return -1;
}
if (left.val > i.left.val) {
return 1;
}
if (left.isClose && !i.left.isClose) {
return -1;
}
if (!left.isClose && i.left.isClose) {
return 1;
}
return 0;
}
public Endpoint left = new Endpoint();
public Endpoint right = new Endpoint();
}
public static List<ExInterval> unionExIntervals(List<ExInterval> I) {
// Empty input.
List<ExInterval> uni = new ArrayList<>();
if (I.isEmpty()) {
return uni;
}
// Sorts ExIntervals according to their left endpoints.
Collections.sort(I);
ExInterval curr = new ExInterval();
curr = I.get(0);
for (int i = 1; i < I.size(); ++i) {
if (I.get(i).left.val < curr.right.val
|| (I.get(i).left.val == curr.right.val
&& (I.get(i).left.isClose || curr.right.isClose))) {
if (I.get(i).right.val > curr.right.val
|| (I.get(i).right.val == curr.right.val
&& I.get(i).right.isClose)) {
curr.right = I.get(i).right;
}
} else {
uni.add(curr);
curr = I.get(i);
}
}
uni.add(curr);
return uni;
}