Topic:
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]
.
Test instructions
Sets the set of intervals, merging all the repeating intervals.
Like what
Given [1,3],[2,6],[8,10],[15,18]
,
Return [1,6],[8,10],[15,18]
.
Algorithm Analysis:
Reference Blog Http://www.cnblogs.com/springfor/p/3872332.html?utm_source=tuicool
The main difficulty of this problem is to rewrite comparator.
The comparator interface defines two methods: compare () and Equals (). The Compare () method presented here compares two elements sequentially:
int compare (object Obj1, Object obj2)
Obj1 and Obj2 are the two objects being compared. When two objects are equal, the method returns 0, and when OBJ1 is greater than obj2, a positive value is returned, otherwise a negative value is returned. If the type of the object being used for comparison is incompatible, the method throws a ClassCastException exception. by overwriting compare (), you can change the way objects are sorted. For example, by creating a comparison function that reverses the comparison output, you can sort by reverse.
The Equals () method given here tests whether an object is equal to the call comparison function:
Boolean equals (Object obj)
Obj is an object that is used for equality testing. If both obj and the calling object are comparator objects and use the same sort. The method returns True. Otherwise, false is returned. Overloading the Equals () method is not necessary, and most simple comparison functions do not.
AC Code:
public class Solution {public list<interval> merge (list<interval> intervals) {if (intervals = = N ull | | Intervals.size () <= 1) return intervals; Sort intervals by using self-defined Comparator collections.sort (intervals, new Intervalcomparator ()); arraylist<interval> result = new arraylist<interval> (); Interval prev = intervals.get (0); for (int i = 1; i < intervals.size (); i++) {Interval Curr = Intervals.get (i); if (prev.end >= curr.start) {//merged case Interval merged = new Interval (p Rev.start, Math.max (Prev.end, curr.end)); prev = merged; } else {result.add (prev); prev = Curr; }} result.add (prev); return result; }}class Intervalcomparator implements comparator<interval>{public int compare(Interval i1, Interval i2) {return i1.start-i2.start; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Merge intervals