# Merge Intervals

46人阅读 评论(0)

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].

/**
* 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) {

ArrayList<Interval> result = new ArrayList<Interval>();
if (intervals == null || intervals.size() <= 1)
return intervals;

Comparator<Interval> comp = new Comparator<Interval>() {
public int compare(Interval i1, Interval i2) {
return i1.start - i2.start;
}
};
Collections.sort(intervals, comp);

for (int i = 1; i < intervals.size(); i++) {
if (result.get(result.size() - 1).end >= intervals.get(i).start) {
result.get(result.size() - 1).end = Math.max(intervals.get(i).end, result.get(result.size() - 1).end);
} else {
}
}

return result;
}

}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：6026次
• 积分：789
• 等级：
• 排名：千里之外
• 原创：77篇
• 转载：1篇
• 译文：0篇
• 评论：0条
文章存档
阅读排行
评论排行