題目大意:code
一個座標軸,給你n個範圍,把重疊的範圍合併,返回合併後的座標對排序
思路:ip
先排序,再遍歷判斷下一個開始是否在上一個範圍內,若是在且結束座標大於上一個座標就合併leetcode
Java實現:get
public List<Interval> merge(List<Interval> intervals) { if (intervals == null || intervals.size() == 0) return intervals; // sort intervals = intervals.stream() .sorted(Comparator.comparing(e -> e.start)) .collect(Collectors.toList()); List<Interval> result = new ArrayList<>(); int start = intervals.get(0).start; int end = intervals.get(0).end; for (int i = 1; i < intervals.size(); i++) { Interval tmp = intervals.get(i); if (tmp.start >= start && tmp.start <= end) { if (tmp.end > end) end = tmp.end; } else { result.add(new Interval(start, end)); start = tmp.start; end = tmp.end; } } result.add(new Interval(start, end)); return result; }