码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Merge Intervals

时间:2014-05-16 08:44:29      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

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

bubuko.com,布布扣
public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        if(intervals.isEmpty())
            return intervals;
        Collections.sort(intervals, new IntervalComparator());
        Interval pre = intervals.get(0);
        for(int i=1;i<intervals.size();i++){
            Interval temp = intervals.get(i);
            int start = pre.start;
            int end = pre.end;
            if(temp.start>end){
                pre=temp;
                continue;
            }else if(temp.start==end){
                pre.end=temp.end;
                intervals.remove(temp);
                i--;
                continue;
            }else{
                if(temp.start>=start&&temp.end>=end){
                    temp.start=start;
                    intervals.remove(pre);
                    pre = temp;
                    i--;
                    continue;
                    
                }else if(temp.start>=start&&temp.end<=end){
                    temp.start=start;
                    temp.end=end;
                    intervals.remove(pre);
                    pre=temp;
                    i--;
                    continue;
                }else if(temp.start<=start&&temp.end>=end){
                    intervals.remove(pre);
                    pre=temp;
                    i--;
                    continue;
                }else if(temp.start<=start&&temp.end>start&&end>temp.end){
                    temp.end=end;
                    intervals.remove(pre);
                    pre=temp;
                    i--;
                    continue;
                }
            }
        }
        return intervals;
        
    }
    
    
}
class IntervalComparator implements Comparator<Interval>
{
    public int compare(Interval a, Interval b) {
        return a.start - b.start;
    }
}
bubuko.com,布布扣

 

【LeetCode】Merge Intervals,布布扣,bubuko.com

【LeetCode】Merge Intervals

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/yixianyixian/p/3725889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!