-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathMerge_common_intervals.java
51 lines (49 loc) · 1.34 KB
/
Merge_common_intervals.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public int[][] merge(int[][] arr) {
Stack<Pair>st=new Stack<>();
Pair[] pairs=new Pair[arr.length];
for(int i=0;i<arr.length;i++){
pairs[i]=new Pair(arr[i][0],arr[i][1]);
}
Arrays.sort(pairs);
for(int i=0;i<pairs.length;i++){
if(i==0)
st.push(pairs[i]);
else{
Pair top=st.peek();
Pair curr=pairs[i];
if(top.et<curr.st)
st.push(curr);
else
top.et=Math.max(curr.et,top.et);
}
}
Stack<Pair>rs=new Stack<>();
int j=0;
while(st.size()>0){
rs.push(st.pop());
j++;
}
int [][] merge=new int[j][2];
for(int i=0;i<merge.length;i++){
Pair top=rs.pop();
merge[i][0]=top.st;
merge[i][1]=top.et;
}
return merge;
}
public static class Pair implements Comparable<Pair>{
int st;
int et;
public Pair(int st,int et){
this.st=st;
this.et=et;
}
public int compareTo(Pair other){
if(this.st!=other.st)
return this.st-other.st;
else
return this.et-other.et;
}
}
}