- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathMerge_Interval.java
More file actions
Latest commit
74 lines (73 loc) · 2.04 KB
/
Copy pathMerge_Interval.java
File metadata and controls
74 lines (73 loc) · 2.04 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// A Java program for merging overlapping intervals
/*Name : Atul Kumar
Github username : atul1510
Repositary name : Algorithms
*/
//Problem Statement : Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals,
//and return an array of the non-overlapping intervals that cover all the intervals in the input.
importjava.util.Arrays;
importjava.util.Comparator;
importjava.util.Stack;
publicclassMerge_Interval {
// The main function that takes a set of intervals, merges
// overlapping intervals and prints the result
publicstaticvoidmergeIntervals(Intervalarr[])
{
// Test if the given set has at least one interval
if (arr.length <= 0)
return;
// Create an empty stack of intervals
Stack<Interval> stack=newStack<>();
// sort the intervals in increasing order of start time
Arrays.sort(arr,newComparator<Interval>(){
publicintcompare(Intervali1,Intervali2)
{
returni1.start-i2.start;
}
});
// push the first interval to stack
stack.push(arr[0]);
// Start from the next interval and merge if necessary
for (inti = 1 ; i < arr.length; i++)
{
// get interval from stack top
Intervaltop = stack.peek();
// if current interval is not overlapping with stack top,
// push it to the stack
if (top.end < arr[i].start)
stack.push(arr[i]);
// Otherwise update the ending time of top if ending of current
// interval is more
elseif (top.end < arr[i].end)
{
top.end = arr[i].end;
stack.pop();
stack.push(top);
}
}
// Print contents of stack
System.out.print("The Merged Intervals are: ");
while (!stack.isEmpty())
{
Intervalt = stack.pop();
System.out.print("["+t.start+","+t.end+"] ");
}
}
publicstaticvoidmain(Stringargs[]) {
Intervalarr[]=newInterval[4];
arr[0]=newInterval(1,3);
arr[1]=newInterval(2,6);
arr[2]=newInterval(8,10);
arr[3]=newInterval(15,18);
mergeIntervals(arr);
}
}
publicclassInterval
{
intstart,end;
Interval(intstart, intend)
{
this.start=start;
this.end=end;
}
}