Skip to content

Commit bda4964

Browse files
committed
add: MergeOverlappingIntervals
1 parent 5ef5c80 commit bda4964

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.ArrayList;
2+
import java.util.Collections;
3+
import java.util.List;
4+
5+
import DS.Interval;
6+
7+
/*
8+
// Definition of Interval:
9+
class Interval {
10+
public int start;
11+
public int end;
12+
public Interval(int start, int end) {
13+
this.start = start;
14+
this.end = end;
15+
}
16+
}
17+
*/
18+
19+
public class MergeOverlappingIntervals {
20+
public List<Interval> mergeOverlappingIntervals(List<Interval> intervals) {
21+
Collections.sort(intervals, (a, b) -> Integer.compare(a.start, b.start));
22+
List<Interval> merged = new ArrayList<>();
23+
merged.add(intervals.get(0));
24+
for (int i = 1; i < intervals.size(); i++) {
25+
Interval B = intervals.get(i);
26+
Interval A = merged.get(merged.size() - 1);
27+
// If A and B don't overlap, add B to the merged list.
28+
if (A.end < B.start) {
29+
merged.add(B);
30+
}
31+
// If they do overlap, merge A with B.
32+
else {
33+
A.end = Math.max(A.end, B.end);
34+
}
35+
}
36+
return merged;
37+
}
38+
}

0 commit comments

Comments
 (0)