-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeIntervals.java
41 lines (35 loc) · 1.11 KB
/
MergeIntervals.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
import java.util.* ;
import java.io.*;
/*******************************************************
Following is the Interval class structure
class Interval {
int start, int finish;
Interval(int start, int finish) {
this.start = start;
this.finish = finish;
}
}
*******************************************************/
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static List<Interval> mergeIntervals(Interval[] intervals) {
// write your code here.
Arrays.sort(intervals, (a, b) -> a.start - b.start);
ArrayList<Interval> result = new ArrayList<Interval>();
int i , j;
for(i = 0; i < intervals.length;)
{
j = i + 1;
while(j < intervals.length && intervals[j].start < 1 + intervals[i].finish)
{
intervals[i].finish = Math.max(intervals[i].finish , intervals[j].finish);
++j;
}
result.add(intervals[i]);
i = j;
}
return result;
}
}