Skip to content

Commit 5005aa3

Browse files
committed
feat: leetcode 56
1 parent 7c588c0 commit 5005aa3

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.ggggght.learningjava8.leetcode;
2+
3+
import java.util.Collections;
4+
import java.util.Comparator;
5+
import java.util.LinkedList;
6+
import java.util.PriorityQueue;
7+
8+
/**
9+
* <pre>
10+
*
11+
* 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.
12+
*
13+
*
14+
*
15+
* Example 1:
16+
*
17+
* Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
18+
* Output: [[1,6],[8,10],[15,18]]
19+
* Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
20+
* Example 2:
21+
*
22+
* Input: intervals = [[1,4],[4,5]]
23+
* Output: [[1,5]]
24+
* Explanation: Intervals [1,4] and [4,5] are considered overlapping.
25+
*
26+
*
27+
* Constraints:
28+
*
29+
* 1 <= intervals.length <= 104
30+
* intervals[i].length == 2
31+
* 0 <= starti <= endi <= 104
32+
* </pre>
33+
*
34+
*/
35+
public class Leetcode56 {
36+
/**
37+
* 使用优先队列进行排序对所有的区间进行排序 排序完成之后, 依次遍历第一个元素的第二项, 如果和上一项有重叠, 则更新, 否则就添加当前项
38+
* @param intervals
39+
* @return
40+
*/
41+
public int[][] merge(int[][] intervals) {
42+
PriorityQueue<int[]> q = new PriorityQueue<>(intervals.length, Comparator.comparingInt(o -> o[0]));
43+
Collections.addAll(q, intervals);
44+
LinkedList<int[]> res = new LinkedList<>();
45+
res.add(q.poll());
46+
while (!q.isEmpty()) {
47+
var poll = q.poll();
48+
var last = res.getLast();
49+
if (poll[0] <= last[1]) {
50+
if (poll[1] > last[1]) {
51+
last[1] = poll[1];
52+
res.set(res.size() - 1, last);
53+
}
54+
} else {
55+
res.add(poll);
56+
}
57+
}
58+
59+
return res.toArray(new int[0][0]);
60+
}
61+
}

0 commit comments

Comments
 (0)