forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeOverlappingArray.java
78 lines (65 loc) · 1.55 KB
/
MergeOverlappingArray.java
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
74
75
76
77
78
//Given a collection of intervals, merge all overlapping intervals.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MergeOverlappingArray {
public static int[][] merge(int[][] intervals) {
List<int[]> list = new ArrayList<>();
if (intervals.length == 0 || intervals == null)
list.toArray(new int[0][]);
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
int begin = intervals[0][0];
int end = intervals[0][1];
for (int [] j : intervals) {
if (j[0] <= end) {
end = Math.max(end, j[1]);
} else {
list.add(new int[] {begin, end});
begin = j[0];
end = j[1];
}
}
list.add(new int[] {begin, end});
intervals = list.toArray(new int[0][]);
return intervals;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of intervals: ");
int n = sc.nextInt();
System.out.println("Enter intervals: ");
int[][] arr = new int[n][2];
for (int k = 0; k < arr.length; k++) {
for (int l = 0; l < arr[k].length; l++) {
arr[k][l] = sc.nextInt();
}
}
int[][] t = merge(arr);
for (int[] row : t) {
System.out.println(Arrays.toString(row));
}
sc.close();
}
}
/*
Input and Output of Program
Enter the number of intervals:
2
Enter intervals:
1 8
2 7
[1, 8]
Enter the number of intervals:
4
Enter intervals:
1 3
2 6
8 10
15 18
[1, 6]
[8, 10]
[15, 18]
Time Complexity: O(nlogn) + O(n)
Space Complexity: O(n)
*/