Skip to content

Instantly share code, notes, and snippets.

@ElninoFong
Created February 20, 2015 06:30
Show Gist options
  • Save ElninoFong/61ed679060c9a189d64b to your computer and use it in GitHub Desktop.
Save ElninoFong/61ed679060c9a189d64b 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> res = new ArrayList<>();
if (intervals == null || intervals.size() == 0) {
return res;
}
Collections.sort(intervals, new MyComparator());
Interval prev = intervals.get(0);
for (int i = 1; i < intervals.size(); i++) {
Interval curr = intervals.get(i);
if (prev.end < curr.start) {
res.add(prev);
prev = curr;
} else if (prev.end < curr.end) {
prev.end = curr.end;
}
}
res.add(prev);
return res;
}
private class MyComparator implements Comparator<Interval> {
public int compare(Interval l1, Interval l2) {
return l1.start - l2.start;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment