使用 领扣中国,来获得适合您的内容以及最佳的用户体验。
即刻前往 | 将我的账号同步到 LeetCode 中国
LeetCode
Explore
Problems
Mock
Contest
Articles
Discuss
Store
Premium
New Playground
lifeqiuzhi520
1133 92
56. Merge Intervals
DescriptionHintsSubmissionsDiscussSolution
Pick One
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 considerred overlapping.
Seen this question in a real interview before? YesNo
Difficulty:Medium
Total Accepted:235.4K
Total Submissions:714K
Contributor:LeetCode
Subscribe to see which companies asked this question.
Related Topics
ArraySort
Similar Questions
Insert IntervalMeeting RoomsMeeting Rooms IITeemo AttackingAdd Bold Tag in StringRange ModuleEmployee Free TimePartition Labels
Java
1
/**
2
* Definition for an interval.
3
* public class Interval {
4
* int start;
5
* int end;
6
* Interval() { start = 0; end = 0; }
7
* Interval(int s, int e) { start = s; end = e; }
8
* }
9
*/
10
class Solution {
11
12
public List<Interval> merge(List<Interval> intervals) {
13
if (intervals == null || intervals.isEmpty()) {
14
return new ArrayList<>();
15
}
16
Collections.sort(intervals, new Comparator<Interval>() {
17
@Override
18
public int compare(Interval o1, Interval o2) {
19
if (o1.start < o2.start) {
20
return -1;
21
}
22
if (o1.start == o2.start) {
23
return 0;
24
}
25
return 1;
26
}
27
});
28
Stack<Interval> intervals1 = new Stack<>();
29
intervals1.add(intervals.get(0));
30
for (int i = 1; i < intervals.size(); i++) {
31
Interval peek = intervals1.peek();
32
Interval item = intervals.get(i);
33
if (peek.end >= item.start) {
34
35
intervals1.pop();
36
if (item.end < peek.end) {
37
intervals1.add(new Interval(peek.start, peek.end));
38
}else {
39
intervals1.add(new Interval(peek.start, item.end));
40
}
41
42
43
} else {
44
intervals1.add(item);
45
}
46
47
}
48
return new ArrayList<>(intervals1);
49
50
}
51
52
}
Custom Testcase( Contribute )
Run Code Submit Solution
Notes
|||
Type here...(Markdown is enabled)
Copyright © 2018 LeetCode Contact Us | Jobs | Frequently Asked Questions | Terms of Service | Privacy Policy
译