Leetcode 56. Merge Intervals

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值