题解 | #合并区间#

合并区间

https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

import java.util.*;

/*
 * public class Interval {
 *   int start;
 *   int end;
 *   public Interval(int start, int end) {
 *     this.start = start;
 *     this.end = end;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param intervals Interval类ArrayList
     * @return Interval类ArrayList
     */
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        if (intervals == null || intervals.isEmpty()) {
            return intervals;
        }
        // 排序
        intervals.sort(Comparator.comparingInt(obj -> ((Interval)obj).start).thenComparingInt(obj -> ((Interval) obj).end));
        //合并
        LinkedList<Interval> rst = new LinkedList<>();
        rst.add(intervals.get(0));
        for (int i = 1; i < intervals.size(); i++) {
            Interval last = rst.peekLast(); // 检索最后一个元素
            if (last == null) {
                continue;
            }
            Interval o = intervals.get(i);
            if (last.end >= o.end) { // 前一个对象的end比后一个对象的end更大,则无需合并
                continue;
            }
            if (last.end >= o.start) { // 前一个对象的end比后一个对象的end更小,start更大则需合并,并加入集合
                rst.pollLast(); // 检索并删除最后一个元素
                rst.offerLast(new Interval(last.start, o.end));
                continue;
            }
            rst.offerLast(o); // 前一个对象的end比后一个对象的start更小则无需合并,则加入集合
        }
        return new ArrayList<>(rst);
    }

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务