"057-insert Interval (insertion interval)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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 in as [2,5]
[1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge in as [4,9]
[1,2],[3,10],[12,16]
.
This is because, the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
Main Topic
Given a series of non-covered intervals, a new interval is inserted, the interval is merged when necessary, and the interval begins with the merging of the starting time.
Thinking of solving problems
If the original interval is smaller than the insertion interval, insert the result set, if the insertion interval overlaps, update the insertion interval, if the insertion interval is smaller than the original interval, insert the insertion interval, and then add a larger interval
Code Implementation
Algorithm implementation class
ImportJava.util.LinkedList;ImportJava.util.List; Public class solution { PublicList<interval>Insert(list<interval> intervals, Interval newinterval) {//Save a collection of resultslist<interval> result =NewLinkedlist<> ();//Input set non-empty if(Intervals! =NULL) {//Traversal element for(Interval item:intervals) {//NewInterval = = NULL indicates that the insertion interval has been processed //The result set will be added to the interval smaller than the insertion interval if(NewInterval = =NULL|| Item.end < Newinterval.start) {Result.add (item); }//The interval larger than the insertion interval is added to the result set, and the inserted interval is added to the result sets Else if(Item.Start > Newinterval.end) {Result.add (newinterval); Result.add (item); NewInterval =NULL; }//Insert interval overlapping, update insertion interval Else{Newinterval.start = Math.min (Newinterval.start, Item.Start); Newinterval.end = Math.max (Newinterval.end, item.end); } } }//If the insertion interval is non-null, the insertion interval has not been processed if(NewInterval! =NULL) {Result.add (newinterval); }returnResult }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47164431"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "057-insert Interval (insertion interval)"