|
1 | 1 | package arrays; |
2 | | -/* Problem Title :-> */ |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +/* Problem Title :-> Merge Intervals */ |
3 | 5 | public class Array_Problem_14 { |
| 6 | + //The main function that takes a set of intervals, merges overlapping intervals & prints the result. |
| 7 | + public static void mergeIntervals(Interval[] a){ |
| 8 | + //Test if the given set has at least one interval |
| 9 | + if(a.length <= 0) |
| 10 | + return; |
| 11 | + //Create an empty stack of intervals |
| 12 | + Stack<Interval> stack = new Stack<>(); |
| 13 | + //sort the intervals in increasing order of start time |
| 14 | + Arrays.sort(a, new Comparator<>() { |
| 15 | + public int compare(Interval i1, Interval i2){ |
| 16 | + return i1.start -i2.start; |
| 17 | + } |
| 18 | + }); |
| 19 | + //push the first interval to stack |
| 20 | + stack.push(a[0]); |
| 21 | + //Start from the next interval and merge if necessary |
| 22 | + for(int i = 1; i < a.length; i++){ |
| 23 | + //get interval from stack top |
| 24 | + Interval top = stack.peek(); |
| 25 | + //if current interval is not overlapping with stack top,push it to the stack |
| 26 | + if(top.end < a[i].start) |
| 27 | + stack.push(a[i]); |
| 28 | + //Otherwise update the ending time of top if ending of current interval is more |
| 29 | + else if(top.end < a[i].end){ |
| 30 | + top.end = a[i].end; |
| 31 | + stack.pop(); |
| 32 | + stack.push(top); |
| 33 | + } |
| 34 | + } |
| 35 | + //Print contents of stack |
| 36 | + System.out.print("The Merged Intervals are: "); |
| 37 | + while(!stack.isEmpty()){ |
| 38 | + Interval t = stack.pop(); |
| 39 | + System.out. print("[" + t.start + "," + t.end + "] "); |
| 40 | + } |
| 41 | + } |
| 42 | + public static void main(String[] args) { |
| 43 | + Interval[] a = new Interval[4]; |
| 44 | + a[0] = new Interval(6,8); |
| 45 | + a[1] = new Interval(1,9); |
| 46 | + a[2] = new Interval(2,4); |
| 47 | + a[3] = new Interval(4,7); |
| 48 | + mergeIntervals(a); |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +class Interval{ |
| 53 | + int start, end; |
| 54 | + Interval(int start, int end){ |
| 55 | + this.start = start; |
| 56 | + this.end = end; |
| 57 | + } |
4 | 58 | } |
0 commit comments