Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created December 20, 2012 23:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zac-xin/4349436 to your computer and use it in GitHub Desktop.
Save zac-xin/4349436 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].
/**
* 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