题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
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; }
算法 文章被收录于专栏
数据结构和算法