56. Merge Intervals
2016-03-22 本文已影响94人
宋翰要长肉
Algorithm
- sort intervals according to start time in increasing order
- traverse sorted intervals from first interval
- if current interval is not the first interval and it overlaps the last interval in output list of intervals, merge these two intervals
- update end time of last interval in output list of intervals to maximum of end times of the two intervals.
- else add current interval into output list of intervals
- if current interval is not the first interval and it overlaps the last interval in output list of intervals, merge these two intervals
Complexity
- time complexity: O(NlgN)
- time complexity of sorting: O(NlgN)
- space complexity: O(N)
- space used for output list of intervals
Code
/**
* 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) {
if (intervals == null || intervals.size() == 0) {
return intervals;
}
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval i1, Interval i2) {
return i1.start - i2.start;
}
});
int size = intervals.size();
List<Interval> result = new ArrayList();
result.add(intervals.get(0));
for (int i = 1; i < size; i++) {
Interval first = result.get(result.size() - 1);
Interval second = intervals.get(i);
if (second.start > first.end) {
result.add(second);
} else {
int newEnd = Math.max(first.end, second.end);
first.end = newEnd;
}
}
return result;
}
}