-
-
Save flashfoxter/94da10627d7770cf3dd7cf9b12edf10f to your computer and use it in GitHub Desktop.
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].
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for an interval. | |
* public class Interval { | |
* int start; | |
* int end; | |
* Interval() { start = 0; end = 0; } | |
* Interval(int s, int e) { start = s; end = e; } | |
* } | |
*/ | |
import java.util.*; | |
public class Solution { | |
public ArrayList<Interval> merge(ArrayList<Interval> intervals) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(intervals.size() == 0) | |
return intervals; | |
if(intervals.size() == 1) | |
return intervals; | |
Collections.sort(intervals, new IntervalComparator()); | |
Interval first = intervals.get(0); | |
int start = first.start; | |
int end = first.end; | |
ArrayList<Interval> result = new ArrayList<Interval>(); | |
for(int i = 1; i < intervals.size(); i++){ | |
Interval current = intervals.get(i); | |
if(current.start <= end){ | |
end = Math.max(current.end, end); | |
}else{ | |
result.add(new Interval(start, end)); | |
start = current.start; | |
end = current.end; | |
} | |
} | |
result.add(new Interval(start, end)); | |
return result; | |
} | |
} | |
class IntervalComparator implements Comparator{ | |
public int compare(Object o1, Object o2){ | |
Interval i1 = (Interval)o1; | |
Interval i2 = (Interval)o2; | |
return i1.start - i2.start; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment