Leetcode

# 56. Merge Intervals

by hooni posted May 05, 2020
?

#### 단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

Given a collection of intervals, merge all overlapping intervals.

Example 1:

```Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
```

Example 2:

```Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.```

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

```class Solution {
public int[][] merge(int[][] intervals) {
List<int[]> list = new ArrayList<>();

Collections.sort(Arrays.asList(intervals), Comparator.comparingInt(p -> p[0]));

if(intervals.length > 1){
for(int i=1; i<intervals.length; i++){
if(intervals[i-1][1] >= intervals[i][0]){
int min = Math.min(intervals[i-1][0], intervals[i][0]);
int max = Math.max(intervals[i-1][1], intervals[i][1]);

intervals[i-1][0] = intervals[i][0] = min;
intervals[i-1][1] = intervals[i][1] = max;
}else{
}
}
}
if(intervals.length > 0){
}

int[][] result = new int[list.size()][2];
for(int i=0; i<list.size(); i++){
int[] p = list.get(i);
result[i][0] = p[0];
result[i][1] = p[1];
}

return result;
}
}```

1 2 3 4