Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
思路:
思路跟meeting room很像吧,就是比较start和end的大小而已,不过在评论区看到一个回复,Was asked to solve this question by FB without using the new operator (ie creating new objects). Below is my solution in O(1) space. 然后要避免用get,避免多次遍历。用遍历器去遍历,
Iterator, 如果hasnext, 然后比较prev.end 和 next.start,
public class Solution {
public List<Interval> merge(List<Interval> itv) {
if (itv == null) throw new IllegalArgumentException();
itv.sort((i1, i2) -> Integer.compare(i1.start, i2.start));
Iterator<Interval> it = itv.iterator();
Interval prev = it.hasNext() ? it.next() : null;
while (it.hasNext()) {
Interval next = it.next();
if (prev.end >= next.start) {
prer.end = Math.max(prev.end, next.end);
it.remove();
} else {
prev = next;
}
}
return itv;
}
}