LeetCode 56.
Tags: LeetCode
Complexity
-
Time complexity: O(nlogn)
-
Space complexity: O(n)
Code
class Solution {
public int[][] merge(int[][] intervals) {
List<int[]> result = new ArrayList<>();
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); //nlogn
int start = intervals[0][0], end = intervals[0][1];
for (int i=1; i<intervals.length; i++) {
if (intervals[i][0] <= end && intervals[i][1] > end) {
end = intervals[i][1];
}else if (intervals[i][0] > end) {
result.add(new int[]{start, end});
start = intervals[i][0];
end = intervals[i][1];
}
}
return result.toArray(new int[result.size()][]);
}
}
Check out the description of this problem at LC 56.