标签: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]
.
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; } }
【LeetCode】Merge Intervals,布布扣,bubuko.com
标签:style blog class code c java
原文地址:http://www.cnblogs.com/yixianyixian/p/3725889.html