题解 | 合并区间
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
import java.util.*; import java.util.stream.Collectors; /* * 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) { // write code here // console.log(intervals)]] ArrayList<Interval> ans = new ArrayList<Interval>(); if (intervals.size() == 0) return ans; // 排序 // Collections.sort(intervals, new Comparator<Interval>() { // public int compare(Interval o1, Interval o2) { // if (o1.start != o2.start) { // return o1.start - o2.start; // } else { // return o1.end - o2.end; // } // } // }); List<Interval> its = intervals.stream().sorted(new Comparator<Interval>() { public int compare(Interval o1, Interval o2) { if (o1.start != o2.start) { // System.out.println("www"); return o1.start - o2.start; } else { // System.out.println("xxx"); return o1.end - o2.end; } } }).collect(Collectors.toList()); // its.forEach(i ->System.out.println(i.start + " /" + i.end)); ans.add((its.get(0))); int count = 0; for (int i = 1; i < its.size(); i++) { Interval o1 = its.get((i)); Interval origin = ans.get(count); if (o1.start > origin.end) { ans.add(o1); count++; } else { ans.remove(count); Interval s = new Interval(origin.start, o1.end); if (o1.end < origin.end) s.end = origin.end; ans.add(s); } } return ans; } }