Merge Intervals @LeetCode

Ref : http://fisherlei.blogspot.com/2013/04/leetcode-merge-intervals-solution.html


复用一下Insert Intervals的解法即可。 大家可以看到在此算法中,完整使用了Insert Interval的代码。

http://blog.youkuaiyun.com/imabluefish/article/details/38701089


创建一个新的interval集合,然后每次从旧的里面取一个interval出来,然后插入到新的集合中。

/**
 * 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 merge(List intervals) {
        ArrayList ret = new ArrayList();
        if (intervals == null) {
            return null;
        }
        
        for (Interval newInterval: intervals) {
            ret = insert(ret, newInterval);
        }
        
        return ret;
    }
    
    public ArrayList insert(List intervals, Interval newInterval) {
        ArrayList ret = new ArrayList();
        if (intervals == null) {
            return null;
        }
        
        Interval last = newInterval;
        
        for (int i = 0; i < intervals.size(); i++) {
            Interval curr = intervals.get(i);
            
            // if curr is on the left of last.
            if (curr.end < last.start) {
                ret.add(curr);
            // if curr is on the right of last.
            } else if (curr.start > last.end) {
                ret.add(last);
                last = curr;
            } else {
                last.start = Math.min(last.start, curr.start);
                last.end = Math.max(last.end, curr.end);
            }
        }
        
        ret.add(last);
        
        return ret;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值