LeetCode 59: Merge Intervals

本文介绍了一种用于合并多个区间的方法。通过将区间按起点排序,然后遍历区间进行合并操作,实现了有效地处理区间重叠的问题。该算法适用于日程安排等场景。
/**
 * 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; }
 * }
 */
class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> result = new ArrayList<>();
        if (intervals == null || intervals.size() < 2) {
            return intervals;
        }
        Collections.sort(intervals, new Comparator<Interval>(){
            @Override
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        });
        Interval current = intervals.get(0);
        for (int i = 1; i < intervals.size(); i++) {
            if (current.end >= intervals.get(i).start) {
                current.end = Math.max(current.end, intervals.get(i).end);
            } else {
                result.add(current);
                current = intervals.get(i);
            }
        }
        result.add(current);
        return result;
    }
}

 

 

1. Has to be sorted if originally not sorted.

2. When merge end point, it could be totally covered instead of intersect.

转载于:https://www.cnblogs.com/shuashuashua/p/7403912.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值