Skip to content

Commit 25183f4

Browse files
committed
nextcommit
1 parent 137bd6d commit 25183f4

File tree

1 file changed

+81
-3
lines changed

1 file changed

+81
-3
lines changed
Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,85 @@
11
package revision;
22

3+
import java.util.Arrays;
4+
import java.util.Comparator;
5+
import java.util.Stack;
6+
7+
class Interval {
8+
9+
int start;
10+
int end;
11+
12+
Interval(int start, int end) {
13+
14+
this.start = start;
15+
this.end = end;
16+
}
17+
18+
}
19+
20+
321
public class MergeOverlapInterval {
422

5-
6-
7-
}
23+
24+
public static void mergeinterval(Interval arr[]) {
25+
26+
if (arr.length <= 0) {
27+
return;
28+
}
29+
30+
Arrays.sort(arr, new Comparator<Interval>() {
31+
32+
public int compare(Interval a, Interval b) {
33+
34+
return a.start - b.start;
35+
// here -1,0,1 represent asc,equal,desc..
36+
}
37+
});
38+
39+
Stack<Interval> stk = new Stack<>();
40+
41+
stk.push(arr[0]);
42+
43+
for (int i = 1; i < arr.length; i++) {
44+
45+
Interval top = stk.peek();
46+
47+
if (top.end < arr[i].start) {
48+
49+
stk.push(arr[i]);
50+
} else if (top.end < arr[i].end) {
51+
52+
top.end = arr[i].end;
53+
stk.pop();
54+
stk.push(top);
55+
56+
57+
}
58+
59+
60+
61+
}
62+
63+
while (!stk.isEmpty()) {
64+
Interval ans = stk.pop();
65+
System.out.println(ans.start + " " + ans.end);
66+
}
67+
68+
69+
70+
}
71+
72+
73+
74+
public static void main(String[] args) {
75+
76+
int n = 4;
77+
Interval arr[] = new Interval[n];
78+
arr[0] = new Interval(6, 8);
79+
mergeinterval(arr);
80+
81+
}
82+
83+
84+
85+
}

0 commit comments

Comments
 (0)