Created
September 14, 2014 23:03
-
-
Save sopherwang/0cd882572f31c48782fd 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 ArrayList<Interval> merge(ArrayList<Interval> intervals) | |
{ | |
ArrayList<Interval> result = new ArrayList<Interval>(); | |
if ((intervals == null) || (intervals.size() == 0)) | |
return result; | |
Comparator<Interval> comparator = new Comparator<Interval>() | |
{ | |
@Override | |
public int compare(Interval i1, Interval i2) | |
{ | |
if (i1.start < i2.start) | |
{ | |
return -1; | |
} | |
else if (i1.start > i2.start) | |
{ | |
return 1; | |
} | |
else | |
{ | |
if (i1.end < i2.end) | |
{ | |
return -1; | |
} | |
else if (i1.end > i2.end) | |
{ | |
return 1; | |
} | |
else | |
{ | |
return 0; | |
} | |
} | |
} | |
}; | |
Collections.sort(intervals, comparator); | |
for (int i = 0; i < intervals.size(); i++) | |
{ | |
Interval cur = intervals.get(i); | |
if (result.isEmpty()) | |
{ | |
result.add(cur); | |
} | |
else | |
{ | |
Interval last = result.get(result.size() - 1); | |
if (last.end >= cur.start) | |
{ | |
last.end = Math.max(last.end, cur.end); | |
} | |
else | |
{ | |
result.add(cur); | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment