Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:22
Show Gist options
  • Save HDegano/b98233f414902311320f to your computer and use it in GitHub Desktop.
Save HDegano/b98233f414902311320f to your computer and use it in GitHub Desktop.
Merge Intervals
public class MergeIntervals {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> mergedIntervals = new ArrayList<>();
if(intervals == null || intervals.size() == 0)
return mergedIntervals;
int n = intervals.size();
if(n == 1)
return intervals;
Collections.sort(intervals, new IntervalComparator());
Interval current = intervals.get(0);
for(int i = 1; i < n; ++i){
Interval next = intervals.get(i);
if(next.start <= current.end)
current.end = Math.max(current.end, next.end);
else{
mergedIntervals.add(current);
current = next;
}
}
mergedIntervals.add(current);
return mergedIntervals;
}
public class Interval {
public int start;
public int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
}
public class IntervalComparator implements Comparator<Interval>{
public int compare(Interval first, Interval second){
return first.start - second.start;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment