标签:
Given a list of tuples representing intervals, return the range these intervals
covered.
e.g:
[(1,3), (2,5),(8,9)] should return 5
和 merge interval非常类似
public class Solution { public List<Interval> merge(List<Interval> intervals) { if (intervals == null || intervals.size() <= 1) { return intervals; } Collections.sort(intervals, new IntervalComparator()); int range = 0; int i=0; while(i<intervals.size()) { Interval newint = new Interval(); int newstart = intervals.get(i).start; int newend = intervals.get(i).end; int j=i+1; while(j<intervals.size()&&newend>=intervals.get(j).start) { newend = Math.max(newend,intervals.get(j).end); j++; } newint.start=newstart; newint.end=newend; range + = newint.end-newint.start; if(j!=i+1) i=j; else i++; } return range; } private class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { return a.start - b.start; } } }
标签:
原文地址:http://www.cnblogs.com/hygeia/p/5154462.html