-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathMergeIntervals.java
41 lines (32 loc) · 1.16 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
// https://leetcode.com/problems/merge-intervals
// Time Complexity o(nlogn), Space Complexity O(n)
class MergeInterval {
public int[][] merge(int[][] intervals) {
if(intervals.length == 0 || intervals.length==1){
return intervals;
}
Comparator<int[]> customCompare = new Comparator<>(){
public int compare(int[] a, int[] b){
return a[0] - b[0];
}
};
Arrays.sort(intervals, customCompare); // O(nlogn)
List<int[]> ans = new ArrayList<>();
for(int[] interval: intervals){ // O(n)
if(ans.size() ==0){
ans.add(interval);
} else{
int[] lastInterval = ans.get(ans.size() -1);
if(lastInterval[1] >= interval[0]){
int maxEnd = Math.max(lastInterval[1], interval[1]);
int start = lastInterval[0];
ans.remove(ans.size()-1);
ans.add(new int[]{start, maxEnd});
} else{
ans.add(interval);
}
}
}
return ans.toArray(new int[ans.size()][2]);
}
}