Created
May 24, 2013 12:10
-
-
Save bittib/5643064 to your computer and use it in GitHub Desktop.
Merge Interval 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].
This file contains hidden or 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 ArrayList<Interval> merge(ArrayList<Interval> intervals) { | |
| ArrayList<Interval> list = new ArrayList<Interval>(); | |
| Collections.sort(intervals, new Comparator<Interval>(){ | |
| public int compare(Interval x, Interval y) { | |
| if (x.start == y.start) | |
| return x.end - y.end; | |
| else | |
| return x.start - y.start; | |
| } | |
| }); | |
| for (int i=0; i<intervals.size(); i++){ | |
| Interval x = intervals.get(i); | |
| while (i+1 < intervals.size() && intervals.get(i+1).start <= x.end){ | |
| x.end = Math.max(x.end, intervals.get(i+1).end); | |
| i++; | |
| } | |
| list.add(x); | |
| } | |
| return list; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment