MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / merge

Method merge

Java/Stack/MergeIntervals.java:15–37  ·  view source on GitHub ↗
(int[][] intervals)

Source from the content-addressed store, hash-verified

13
14class 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}

Callers

nothing calls this directly

Calls 6

pushMethod · 0.95
peekMethod · 0.95
popMethod · 0.95
compareMethod · 0.80
sortMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected