Merge Intervals

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].

语法

Collections.sort operates on a List
Arrays.sort operates on an array

图解

代码

class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        Collections.sort(intervals, (o1, o2)-> o1.start - o2.start);

        List<Interval> result = new ArrayList<>();

        Interval pre = null;
        for(Interval interval : intervals){
            if(pre == null || interval.start > pre.end){
                result.add(interval);
                pre = interval;
            }else{
                pre.end = Math.max(pre.end, interval.end);
            }
        }
        return result;
    }
}

results matching ""

    No results matching ""