Skip to content

Commit 614fef7

Browse files
committed
solve 56.merge-intervals
1 parent 7bb2d82 commit 614fef7

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

vscode/56.merge-intervals.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* @lc app=leetcode id=56 lang=java
3+
*
4+
* [56] Merge Intervals
5+
*
6+
* https://leetcode.com/problems/merge-intervals/description/
7+
*
8+
* algorithms
9+
* Medium (35.46%)
10+
* Likes: 2345
11+
* Dislikes: 183
12+
* Total Accepted: 380.4K
13+
* Total Submissions: 1.1M
14+
* Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]'
15+
*
16+
* Given a collection of intervals, merge all overlapping intervals.
17+
*
18+
* Example 1:
19+
*
20+
*
21+
* Input: [[1,3],[2,6],[8,10],[15,18]]
22+
* Output: [[1,6],[8,10],[15,18]]
23+
* Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into
24+
* [1,6].
25+
*
26+
*
27+
* Example 2:
28+
*
29+
*
30+
* Input: [[1,4],[4,5]]
31+
* Output: [[1,5]]
32+
* Explanation: Intervals [1,4] and [4,5] are considered overlapping.
33+
*
34+
* NOTE: input types have been changed on April 15, 2019. Please reset to
35+
* default code definition to get new method signature.
36+
*
37+
*/
38+
class Solution {
39+
public int[][] merge(int[][] intervals) {
40+
if (intervals.length <= 1) {
41+
return intervals;
42+
}
43+
44+
Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0]));
45+
46+
List<int[]> result = new ArrayList<>();
47+
int[] last = intervals[0];
48+
result.add(last);
49+
50+
for (int i = 1; i < intervals.length; i++) {
51+
int[] interval = intervals[i];
52+
if (last[1] < interval[0]) {
53+
result.add(interval);
54+
last = interval;
55+
} else if (last[1] < interval[1]) {
56+
last[1] = interval[1];
57+
}
58+
}
59+
60+
return result.toArray(new int[result.size()][]);
61+
}
62+
}
63+

0 commit comments

Comments
 (0)