Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
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] .
Test instructions: Merges an interval.
Ideas: The situation: first if for New,end < Cur.start, then it is easy to know that should be inserted in front of cur: Conversely, if New.start > Cur.end words, then can continue to go down, otherwise this is the case: at this time, two intervals are overlapping, each take the left and right boundary of the minimum and maximum value.
Package Code;import Java.util.arraylist;import Java.util.list;import java.util.listiterator;public class Insert_ Interval {public static void main (string[] args) {list<interval> intervals = new Arraylist<insert_ Interval.interval> (); Insert_interval root = new Insert_interval (); insert_interval.interval S1 = root.new Interval (1 , 3); Intervals.add (S1); Intervals.add (new Insert_interval (). New Interval (6, 9)); Insert_interval.interval T = root.new Interval (2, 5); Insert_interval.solution solution = Root.new solution (); list<interval> ans = solution.insert (intervals, t); for (Interval Interval:ans) {System.out.println ( Interval.start + "-" + Interval.end);}} public class Interval {int start; int end; Interval () {start = 0; end = 0;} Interval (int s, int e) {start = s; end = e;}} public class Solution {public list<interval> Insert (list<interval> intervals, Interval newinterval) {i F (intervals = = NULL | | newinterval = = NULL) return intervals; if (intervalS.size () = = 0) intervals.add (newinterval); Listiterator<interval> it = Intervals.listiterator (); while (It.hasnext ()) {Interval tmp = It.next (); if (Newinterval.end < Tmp.start) {it.previous (); It.add (NewInterval); return intervals; } else {if (Newinterval.start > Tmp.end) continue; else {Newinterval.start = Math.min (Tmp.start, Newinterval.start); Newinterval.end = Math.max (Tmp.end, newinterval.end); It.remove (); }}} intervals.add (NewInterval); return intervals; }}}
Leetcode Insert Interval