Last active
August 29, 2015 14:22
-
-
Save HDegano/b98233f414902311320f to your computer and use it in GitHub Desktop.
Merge Intervals
This file contains 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
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