题解 | #合并区间#

合并区间

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

import java.util.*;
/**
 * 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 ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        ArrayList<Interval> result = new ArrayList<>();

        if (intervals == null || intervals.size() == 0) {
            return result;
        }

        //对区间按区间起点排序
        intervals.sort(Comparator.comparingInt(interval -> interval.start));

        Interval temp = intervals.get(0);
        for (int i = 1; i < intervals.size(); i++) {
            Interval interval = intervals.get(i);
            if (interval.start > temp.end ) {
                result.add(temp);
                temp = interval;
            } else if (interval.end > temp.end) {
                temp = new Interval(temp.start, interval.end);
            }
        }
        result.add(temp);
        return result;
    }
}

#在找工作求抱抱#
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:16
科大讯飞 算法工程师 28.0k*14.0, 百分之三十是绩效,惯例只发0.9
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务