"056-merge intervals (interval merger)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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]
.
Main Topic
Given a set of intervals, the overlapping intervals are merged.
Thinking of solving problems
The interval is sorted first, sorted by the start point, and then merged by one.
Code Implementation
Algorithm implementation class
Importjava.util.*; Public class solution { PublicList<interval>Merge(list<interval> intervals) {list<interval> result =NewLinkedlist<> ();if(Intervals = =NULL|| Intervals.size () <1) {returnResult }//Sort the interval first, using an anonymous inner classCollections.sort (intervals,NewComparator<interval> () {@Override Public int Compare(Interval O1, Interval O2) {returnO1.start-o2.start; } });After sorting, the start of the latter element (recorded as Next) must be no less than the previous (recorded as prev) Start, //For the newly added interval, if the Next.start is greater than prev.end, the two intervals are separate, to add //Add a new interval, otherwise the description next.start in [Prev.start, Prev.end], then just look //Next.end is greater than prev.end, if greater than is necessary to merge the interval (enlarge)Interval prev =NULL; for(Interval item:intervals) {if(prev = =NULL|| Prev.end < Item.Start) {Result.add (item); prev = Item; }Else if(Prev.end < Item.end) {prev.end = Item.end; } }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/47120501"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "056-merge intervals (interval merge)"