Range of Intervals

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Range of Intervals相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

C++ 运行时终止 std::out_of_range [关闭]

leetcode327. Count of Range Sum

比较字符串中的符号时出现 std::out_of_range 错误

Microsoft C++ 异常:内存位置的 std::out_of_range

TP5报如下的错误 Indirect modification of overloaded element of thinkpaginatorCollection has no effect(代码片段

查找 std::vector.at() 抛出 std::out_of_range 的位置