关闭

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);
        
        result.add(intervals.get(0));
        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 {
                result.add(intervals.get(i));
            }
        }
        
        
        return result;
    }
    
}


0
0

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