-
Notifications
You must be signed in to change notification settings - Fork 0
/
day19_4.java
85 lines (65 loc) · 1.71 KB
/
day19_4.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
79
80
81
82
83
84
85
/*
Given a collection of Intervals, the task is to merge all of the overlapping Intervals.
Example 1:
Input:
Intervals = {{1,3},{2,4},{6,8},{9,10}}
Output: {{1, 4}, {6, 8}, {9, 10}}
Explanation: Given intervals: [1,3],[2,4]
[6,8],[9,10], we have only two overlapping
intervals here,[1,3] and [2,4]. Therefore
we will merge these two and return [1,4],
[6,8], [9,10].
*/
class Solution
{
public int[][] overlappedInterval(int[][] arr)
{
// Code here // Code here
//i+++++ and j=0,1
Arrays.sort(arr, new Comparator<int[]>()
{
@Override
public int compare(int[] i, int[] j)
{
if(i[0]>j[0])
{
return 1;
}
else
{
return -1;
}
}
}
);
ArrayList<int[]> a = new ArrayList<>();
int start = arr[0][0];
int end = arr[0][1];
if(arr.length ==1)
{
int[][] ans = {{start,end}};
return ans;
}
int prev[] = arr[0];
for(int i=1; i<arr.length ; i++)
{
int[] curr = arr[i];
if(curr[0]<=prev[1])
{
prev[1] = Math.max(curr[1],prev[1]);
}
else
{
a.add(prev);
prev = curr;
}
}
a.add(prev);
int[][] ans = new int[a.size()][2];
for(int i=0; i<a.size(); i++)
{
ans[i] = a.get(i);
}
return ans;
}
}