Given a collection of intervals, merge all overlapping intervals.
For example,
Given
return
Given
[1,3],[2,6],[8,10],[15,18]
,return
[1,6],[8,10],[15,18]
.Solution:
/** * 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) { Collections.sort(intervals, new Comparator<Interval>() { public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } }); int i=1; while(i<intervals.size()) { if (intervals.get(i-1).end >= intervals.get(i).start) { intervals.get(i-1).end = Math.max(intervals.get(i-1).end, intervals.get(i).end); intervals.remove(i); } else i++; } return intervals; } }
No comments :
Post a Comment