public static ArrayList<Interval> merge(ArrayList<Interval> intervals) { intervals.sort(new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { return o1.start - o2.start; } }); int j = 1; int i = 0; while (j < intervals.size()) { Interval before = intervals.get(i); Interval after = intervals.get(j); if (before.end >= after.start) { Interval tmp = new Interval(before.start, Math.max(before.end, after.end)); intervals.remove(i); // 重点删除后,位置会往后移 intervals.remove(i); intervals.add(i, tmp); // 重点add, 不是set } else { i++; j++; } } return intervals; }