意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

LeetCode-Interval List Intersections

来源:恒创科技 编辑:恒创科技编辑部
2024-01-25 22:28:59


Description:
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.


LeetCode-Interval List Intersections

(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)

Example 1:

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]]
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.

Note:

0 <= A.length < 10000 <= B.length < 10000 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9

题意:给定两个序列,每个序列中的元素为一个闭合区间,要求计算这两个序列中所有元素的交集;

解法:因为序列中的元素区间已经按照坐标的大小排好序了,所以我们只需要同时遍历这两个序列,对每两个元素求取他们的区间交集;所以,问题的重点在于如何求解两个区间的交集,我们知道,如果两个区间有交集,那么其开始端一定是两个区间开始端的最大值,结束端一定是两个区间的结束端的最小值,如下如图所示

LeetCode-Interval List Intersections_sed

Java
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class Solution {
public Interval[] intervalIntersection(Interval[] A, Interval[] B) {
List<Interval> res = new ArrayList<>();
int pa = 0;
int pb = 0;
while (pa < A.length && pb < B.length) {
int st = Math.max(A[pa].start, B[pb].start);
int ed = Math.min(A[pa].end, B[pb].end);
if (st <= ed) {
res.add(new Interval(st, ed));
}
if (A[pa].end < B[pb].end) {
pa++;
} else {
pb++;
}
}

return res.toArray(new Interval[res.size()]);
}
}


上一篇: LeetCode-Squares of a Sorted Array 下一篇: 手机怎么远程登录云服务器?