题解 | #合并区间#
合并区间
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) { // write code here // 按照start进行排序 Collections.sort(intervals , (int1 ,int2)->int1.start - int2.start); // 定义所需变量 int dest = 0,cur = 0,n = intervals.size(),count = 0; // 处理特殊情况:没有数据与只有一个数据 if (n <= 1) { return intervals; } // 开始循环遍历: 思路:从异地到就地 for (cur = 1; cur < n; cur++) { if (intervals.get(cur).start <= intervals.get(dest).end) { intervals.get(dest).start = Math.min(Math.min(intervals.get(dest).start,intervals.get(cur).start),Math.min(intervals.get(dest).end,intervals.get(cur).end)); intervals.get(dest).end = Math.max(Math.max(intervals.get(dest).end,intervals.get(cur).end),Math.max(intervals.get(dest).start,intervals.get(cur).start)); count++; } else { dest++; intervals.get(dest).end = intervals.get(cur).end; intervals.get(dest).start = intervals.get(cur).start; } } // 删除无效数据 for (int i = 0; i < count; i++) { intervals.remove(n - 1 - i); } return intervals; } }