[LeetCode-interview algorithm classic-Java implementation] [056-Merge Intervals (range Merge)], leetcode -- java
[056-Merge Intervals (Merge Intervals )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]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]
.
Theme
Given a set of intervals, merge overlapping intervals.
Solutions
Sort the intervals first, sort by start point, and then merge them one by one.
Code Implementation
Algorithm Implementation class
Import java. util. *; public class Solution {public List <Interval> merge (List <Interval> intervals) {List <Interval> result = new partition List <> (); if (intervals = null | intervals. size () <1) {return result;} // sort the interval first and use an anonymous internal class Collections. sort (intervals, new Comparator <Interval> () {@ Override public int compare (Interval o1, Interval o2) {return o1.start-o2.start ;}}); // after sorting, the start of the last element (marked as next) must be no less than the previous (marked as prev) start, // For the newly added interval, if next. start is greater than prev. the end indicates that the two intervals are separated, and a new interval needs to be added //; otherwise, next. start in [prev. start, prev. end], you only need to read // next. whether end is greater than prev. end. if the value is greater than the value, you need to merge the range (extended) 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 ;}} return result ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting [http://blog.csdn.net/derrantcm/article/details/47120501]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.