MrainW's Home

All things come to those who wait!

0%

LeetCode 56. Merge Intervals

Question

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

https://leetcode.com/problems/merge-intervals/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[][] merge(int[][] intervals) {
List<int[]> res = new ArrayList<>();
if (intervals == null || intervals.length == 0) return new int[0][];
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
int[] cur = intervals[0];
for (int[] next : intervals){
if (cur[1] >= next[0]) cur[1] = Math.max(cur[1], next[1]);
else{
res.add(cur);
cur = next;
}
}
res.add(cur);
return res.toArray(new int[0][]);
}
}

Complexity:

Time complexity: O( nlogn)

Space complexity: O(n)

Welcome to my other publishing channels