1
+ //Trapping water
2
+ Class Interval {
3
+ int id ;
4
+ int s ;
5
+ int e ;
6
+ int t ;
7
+ public Interval (int time , int id , int start , int end ) {
8
+ this .id = id ;
9
+ this .t = time ;
10
+ this .s = start ;
11
+ this .e = end ;
12
+ }
13
+ }
14
+
15
+
16
+ public class MergeOverlappingIntervals {
17
+
18
+ // The main function that takes a set of intervals, merges
19
+ // overlapping intervals and prints the result
20
+ public static void mergeIntervals (List <List <Integer >> vehicleAssignments , int id )
21
+ {
22
+ // Test if the given set has at least one interval
23
+ if (arr .length <= 0 )
24
+ return ;
25
+ Interval [] arr = new Interval [vehicleAssignments .size ()];
26
+ for (int i =0 ; i <vehicleAssignments .size (); i ++) {
27
+ Interval it = new Interval (vehicleAssignments .get (i ).get (0 ), vehicleAssignments .get (i ).get (1 ), vehicleAssignments .get (i ).get (2 ),vehicleAssignments .get (i ).get (3 ));
28
+ arr [i ] = it ;
29
+ }
30
+
31
+ // Create an empty stack of intervals
32
+ Stack <Interval > stack =new Stack <>();
33
+
34
+ // sort the intervals in increasing order of start time
35
+ Arrays .sort (arr ,new Comparator <Interval >(){
36
+ public int compare (Interval i1 ,Interval i2 )
37
+ {
38
+ return i1 .s -i2 .s ;
39
+ }
40
+ });
41
+
42
+ // push the first interval to stack
43
+ stack .push (arr [0 ]);
44
+
45
+ // Start from the next interval and merge if necessary
46
+ for (int i = 1 ; i < arr .length ; i ++)
47
+ {
48
+ // get interval from stack top
49
+ Interval top = stack .peek ();
50
+
51
+ // if current interval is not overlapping with stack top,
52
+ // push it to the stack
53
+ if (top .e < arr [i ].s )
54
+ stack .push (arr [i ]);
55
+
56
+ // Otherwise update the ending time of top if ending of current
57
+ // interval is more
58
+ else if (top .e < arr [i ].e )
59
+ {
60
+ top .e = arr [i ].e ;
61
+ stack .pop ();
62
+ stack .push (top );
63
+ }
64
+ }
65
+
66
+ // Print contents of stack
67
+ System .out .print ("The Merged Intervals are: " );
68
+ while (!stack .isEmpty ())
69
+ {
70
+ Interval t = stack .pop ();
71
+ if (t .id == id ) {
72
+ System .out .print ("[" +t .s +"," +t .e +"] " );
73
+ }
74
+ }
75
+ }
76
+
77
+ public static void main (String args []) {
78
+ List <List <Integer >> list = asList (
79
+ asList (100 ,3005 ,660000 , 660200 ),
80
+ asList (100 ,3006 ,660000 , 660200 ),
81
+ asList (100 ,3007 ,700000 , 700200 ),
82
+ asList (200 ,3008 ,660000 , 660500 )
83
+ );
84
+
85
+ mergeIntervals (list , 100 );
86
+ }
87
+ }
88
+
0 commit comments