标签:style class blog code http tar
Question:
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]
.
---------------------------------------
Solution:
public class Solution { class IntervalAsc implements Comparator<Interval> { public int compare (Interval o1, Interval o2) { if (o1.start != o2.start) return o1.start < o2.start ? -1 : 1; else if (o1.end != o2.end) return o1.end < o2.end ? -1 : 1; else return 0; }} public ArrayList<Interval> merge (ArrayList<Interval> intervals) { Collections.sort(intervals, new IntervalAsc()); ArrayList<Interval> ret = new ArrayList<Interval>(); int n = intervals.size(); if(n==0) return ret; Interval last=intervals.get(0); for(int i=1;i<n;i++){ if(intervals.get(i).start>last.end){ ret.add(new Interval(last.start,last.end)); last=intervals.get(i); }else{ last.end=Math.max(intervals.get(i).end, last.end); } } ret.add(last); return ret; } }
需要注意的以下几点:
[Leetcode] Merge Intevals,布布扣,bubuko.com
标签:style class blog code http tar
原文地址:http://www.cnblogs.com/Phoebe815/p/3786188.html