-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsert interval
67 lines (55 loc) · 1.76 KB
/
Insert interval
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
//Insert interval
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class GFG {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0) {
int n = sc.nextInt();
int a[][] = new int[n][2];
for(int i = 0; i < n; i++) {
a[i][0] = sc.nextInt();
a[i][1] = sc.nextInt();
}
int h[] = new int[2];
h[0] = sc.nextInt();
h[1] = sc.nextInt();
Solution obj = new Solution();
ArrayList<int[]> ans = obj.insertInterval(a, h);
System.out.print("[");
for(int i = 0; i < ans.size(); i++) {
System.out.print("[");
System.out.print(ans.get(i)[0] + "," + ans.get(i)[1]);
System.out.print("]");
if (i != ans.size() - 1) System.out.print(",");
}
System.out.println("]");
System.out.println("~");
}
}
}
class Solution {
static ArrayList<int[]> insertInterval(int[][] intervals, int[] newInterval) {
ArrayList<int[]> res = new ArrayList<>();
int i = 0;
int n = intervals.length;
while(i < n && intervals[i][1] < newInterval[0]) {
res.add(intervals[i]);
i++;
}
while(i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
res.add(newInterval);
while(i < n) {
res.add(intervals[i]);
i++;
}
return res;
}
}