| 13 | |
| 14 | class Solution { |
| 15 | public int[][] merge(int[][] intervals) { |
| 16 | Arrays.sort(intervals, (a,b)-> Integer.compare(a[0], b[0])); //This sorting will sort the meetings according to their start time. |
| 17 | |
| 18 | Stack<int[]> st = new Stack<>(); |
| 19 | st.push(intervals[0]); //Initially, we'll push the first meeting element into the stack. |
| 20 | |
| 21 | for(int i = 1; i < intervals.length; i++){ |
| 22 | if(st.peek()[1] >= intervals[i][0]){ |
| 23 | int[] arr = st.pop(); |
| 24 | arr[1] = Math.max(arr[1], intervals[i][1]); |
| 25 | st.push(arr); |
| 26 | } else { |
| 27 | st.push(intervals[i]); |
| 28 | } |
| 29 | } |
| 30 | int[][] ans = new int[st.size()][2]; |
| 31 | int index = ans.length-1; |
| 32 | while(index >= 0){ |
| 33 | ans[index] = st.pop(); |
| 34 | index--; |
| 35 | } |
| 36 | return ans; |
| 37 | } |
| 38 | } |