leetcode 56 merge intervals

Given a collection of intervals, merge all overlapping intervals.

Example 1:

1
2
3
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:

1
2
3
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considerred overlapping.

  • 先按照start从小到大的顺序排序
  • 设定当前start,end为第一个的值
  • 遍历一遍intervals,在这个过程中更新start,end,每次更新,就把原来的值插入到ans中
  • 注意每次比较的时候不是i不是和i-1去比较,而是和start,end比较
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
41
42
43
44
45
46
47
48
49
50
51

* 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; }
* }
*/
class {
public List<Interval> merge(List<Interval> intervals) {
ArrayList<Interval> ans = new ArrayList<Interval>();

if(intervals.size()==0 || intervals == null){
return ans;
}
Collections.sort(intervals, new Comparator<Interval>(){

public int compare(Interval o1, Interval o2){
if(o1.start < o2.start){
return -1;
}
else if(o1.start > o2.start){
return 1;
}
else{
return 0;
}
}
});
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for(int i=1; i< intervals.size(); i++){
if(intervals.get(i).start <= end && intervals.get(i).end <= end){

}
else if(intervals.get(i).start <= end && intervals.get(i).end > end){
end = intervals.get(i).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;

}
}

讨论区更descent的方法:

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
class  {
private class IntervalComparator implements Comparator<Interval> {

public int compare(Interval a, Interval b) {
return a.start < b.start ? -1 : a.start == b.start ? 0 : 1;
}
}

public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new IntervalComparator());

LinkedList<Interval> merged = new LinkedList<Interval>();
for (Interval interval : intervals) {
// if the list of merged intervals is empty or if the current
// interval does not overlap with the previous, simply append it.
if (merged.isEmpty() || merged.getLast().end < interval.start) {
merged.add(interval);
}
// otherwise, there is overlap, so we merge the current and previous
// intervals.
else {
merged.getLast().end = Math.max(merged.getLast().end, interval.end);
}
}

return merged;
}