模板题目:Interval/Mergelist (986 Interval List Intersections/56 Merge Intervals)
这两道题目 简直就是怪异方法使用大合集 toArray(), copyOf()从来不敢使用 现在 都用上了 现在是时候好好研究一下这几个方法了(其实这种题目比较恶心的点就在于这个容器的转换)
986

Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
class Solution {
public int[][] intervalIntersection(int[][] A, int[][] B) {
List<int[]> ans = new ArrayList();//外层是List 内层是int[] 就是指不知道有多少个int[]对
int i = 0, j = 0;
while (i < A.length && j < B.length) {
// Let's check if A[i] intersects B[j].
// lo - the startpoint of the intersection
// hi - the endpoint of the intersection
int lo = Math.max(A[i][0], B[j][0]); //起点的最大
int hi = Math.min(A[i][1], B[j][1]); //终点的最小
//此时的low high就是可能的交集
if (lo <= hi) //
ans.add(new int[]{lo, hi});
// Remove the interval with the smallest endpoint
if (A[i][1] < B[j][1])
i++;
else
j++;
}
return ans.toArray(new int[ans.size()][]);
}
}
56
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
class Solution {
public int[][] merge(int[][] intervals) {
if (intervals == null || intervals.length <= 1) {
return intervals;
}
List<int[]> res = new ArrayList<>();
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
res.add(intervals[0]);
for (int i = 1; i != intervals.length; i++) {
if (res.get(res.size() - 1)[1] < intervals[i][0]) {
res.add(intervals[i]);
} else {
int left = Math.min(res.get(res.size() - 1)[0], intervals[i][0]);
int right = Math.max(res.get(res.size() - 1)[1], intervals[i][1]);
res.get(res.size() - 1)[0] = left;
res.get(res.size() - 1)[1] = right;
}
}
return res.toArray(new int[res.size()][]);
}
}

浙公网安备 33010602011771号