题解 | #合并区间#
合并区间
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> res = new ArrayList(); // 需要对原集合进行排序 intervals.sort((Interval i1,Interval i2) -> {return i1.start - i2.start;}); // 从头开始 int i = 0; while(i < intervals.size()){ // 最后一个值必定返回 if(i == intervals.size()-1){ res.add(intervals.get(i)); return res; } // 存在多种情况 // 第一种:交接 if(intervals.get(i).end >= intervals.get(i+1).start && intervals.get(i).end < intervals.get(i+1).end){// 第一种:接壤 intervals.get(i+1).start = intervals.get(i).start; i++; }else if(intervals.get(i).end >= intervals.get(i+1).start && intervals.get(i).end >= intervals.get(i+1).end){// 第二种:包含 intervals.get(i+1).start = intervals.get(i).start; intervals.get(i+1).end = intervals.get(i).end; i++; }else{// 第三种:无关,无关时将其加入即可 res.add(intervals.get(i)); i++; } } return res; } }