Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 21, 2016 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/a75a3ff78dbb863774b3b97da0d150f8 to your computer and use it in GitHub Desktop.
Save jianminchen/a75a3ff78dbb863774b3b97da0d150f8 to your computer and use it in GitHub Desktop.
/**
* 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; }
* }
*/
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> result = new ArrayList<Interval>();
if(intervals == null || intervals.size() == 0) return result;
Comparator<Interval> comparator = new Comparator<Interval>(){
public int compare(Interval p, Interval q){
return p.start - q.start;
}
};
Collections.sort(intervals, comparator);
Interval base = intervals.get(0);
for(int i = 1; i < intervals.size(); i++){
Interval current = intervals.get(i);
if(base.end < current.start){
result.add(base);
base = current;
}
base = new Interval(base.start, Math.max(base.end, current.end));
}
result.add(base);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment