p56

LeetCode p56 Merge Intervals 题解

1.题目:

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

题意:

合并所有重叠部分。

2.解题思路:

先排序再覆盖,见代码。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> ans = new ArrayList<Interval>();
if (intervals.size() < 1)
return ans;
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval a, Interval b) {
return (int) (a.start - b.start);
}
});

int start = intervals.get(0).start;
int end = intervals.get(0).end;

for (int i = 0; i < intervals.size() ; i++) {

if (end >= intervals.get(i).start) {
end = Math.max(intervals.get(i).end, end);

} else {
ans.add(new Interval(start, end));
start = intervals.get(i).start;
end = intervals.get(i).end;
}
}
ans.add(new Interval(start, end));
return ans;
}
}

4.一些总结: