"056-merge intervals (interval merger)"
"leetcode-Interview algorithm classic-java Implementation" "All Topics folder 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. Sort by start point, and then merge one at a.
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, assuming that 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]. It's just to see //Next.end is greater than prev.end, assuming 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 }}
Assessment Results
Click on the picture. The mouse does not release, drag a position, and after release, view the full picture in the new form.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47120501"
"Leetcode-Interview algorithm classic-java implementation" "056-merge intervals (interval merge)"