居然debug了两次就过了。。。感动😹
Comparator接口第一次手写还是不熟悉。
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) { Collections.sort(intervals, new Comparator<Interval>(){ @Override public int compare(Interval o1, Interval o2){ return o1.start - o2.start; } }); // 遍历 int pre = 0, cur = 1; if(intervals.size() <= 1) return intervals; int size = intervals.size(); while(cur < size){ if(intervals.get(cur).start <= intervals.get(pre).end){ // 合并 int end = Math.max(intervals.get(cur).end, intervals.get(pre).end); intervals.set(pre, new Interval(intervals.get(pre).start, end)); intervals.remove(cur); size--; }else{ pre++; cur++; } } return intervals; } }