题解 | #合并区间#
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
import java.util.*; /* * public class Interval { * int start; * int end; * public Interval(int start, int end) { * this.start = start; * this.end = end; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param intervals Interval类ArrayList * @return Interval类ArrayList */ public ArrayList<Interval> merge (ArrayList<Interval> intervals) { if (intervals.size() < 1) return intervals; intervals.sort(new Comparator<Interval>() { @Override public int compare(Interval i1, Interval i2) { if (i1.start != i2.start) { return Integer.compare(i1.start, i2.start); } return Integer.compare(i1.end, i2.end); } }); // write code here ArrayList<Interval>list = new ArrayList<>(); if (intervals.get(0).start == 0 && intervals.get(0).end == 0 && intervals.get(1).start > 0) { Interval interval = new Interval(0, 0); list.add(interval); } int min = 0; int max = 0; for (int i = 0; i < intervals.size(); i++) { if (min == 0 && max == 0) { min = intervals.get(i).start; max = intervals.get(i).end; continue; } if (intervals.get(i).start > max) { Interval interval = new Interval(min, max); list.add(interval); min = 0; max = 0; i--; continue; } if (intervals.get(i).start <= max && intervals.get(i).end > max) { max = intervals.get(i).end; } if (intervals.get(i).start < min && intervals.get(i).end > min) { min = intervals.get(i).start; } } Interval interval = new Interval(min, max); list.add(interval); return list; } }