题解 | #合并区间#
合并区间
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; } }#在找工作求抱抱#