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

Range of Intervals

时间:2016-01-24 01:52:18      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

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;
        }
    }
}

 

Range of Intervals

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5154462.html

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