Insert Interval

来源:互联网 发布:长兴岛造船基地 知乎 编辑:程序博客网 时间:2024/06/09 21:47

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge[2,5] in as[1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge[4,9] in as[1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with[3,5],[6,7],[8,10].

代码:

/** * 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; } * } */ class Interval implements Comparable<Interval>{int start;int end;Interval() { start = 0; end = 0; }Interval(int s, int e) { start = s; end = e; }public int compareTo(Interval o){return this.start - o.start;}}public class Solution {    public List<Interval> insert(List<Interval> intervals, Interval newInterval){intervals.add(newInterval);Collections.sort(intervals);List<Interval> result = new ArrayList<Interval>();        int length = intervals.size();        if(length <= 1)        return intervals;        Interval first = intervals.get(0),second = new Interval();        for(int i = 1; i < length; i++)        {        second = intervals.get(i);        if(second.start > first.end)        {        result.add(first);        first = second;        }        else         {        first.end = Math.max(first.end, second.end);}        }        //最后一次合并        result.add(first);        return result;    }}


 

0 0