题解 | #合并区间#
合并区间
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 { // public static void main(Args[] args){ // } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param intervals Interval类ArrayList * @return Interval类ArrayList */ public ArrayList<Interval> merge (ArrayList<Interval> intervals) { Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval i1, Interval i2) { if (i1.start != i2.start) return i1.start - i2.start; else return i1.end - i2.end; } }); // write code here ArrayList<Interval> al = new ArrayList(); for (int i = 0; i < intervals.size(); i++) { Interval outl = new Interval(0, 0); Interval il = intervals.get(i); if (al.size() == 0) { al.add(il); continue; } else { outl = al.get(al.size() - 1); } if (outl.end >= il.start) { // merge al.remove(al.size() - 1); al.add(new Interval(outl.start, Math.max(il.end,outl.end))); continue; } al.add(il); } return al; } }
知识点 :
复杂对象数组类型排序
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval i1, Interval i2) {
if (i1.start != i2.start)
return i1.start - i2.start;
else
return i1.end - i2.end;
}
});
注意边界值