table of Contents
Subject description:
Given by a number of two closed interval lists, each of which pairs are disjoint interval list and sorted.
Returns the intersection of these two sections of the list.
(Formally, the closed interval [a, b]
(where a <= b
) denotes the set of real number x, and a <= x <= b
. Intersection of two closed interval is a set of real numbers, or the empty set, or a closed section for example, [1, 3]
and [2, 4]
the intersection is [2, 3]
.)
Example:
输入:A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
输出:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
注意:输入和所需的输出都是区间对象组成的列表,而不是数组或列表。
prompt:
0 <= A.length < 1000
0 <= B.length < 1000
0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9
solution:
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
int sz1 = A.size();
int sz2 = B.size();
int i = 0, j = 0;
vector<vector<int>> res;
while(i < sz1 && j < sz2){
if(A[i][0] > B[j][1]){
j++;
}else if(A[i][1] < B[j][0]){
i++;
}else{
res.push_back({max(A[i][0], B[j][0]), min(A[i][1], B[j][1])});
if(A[i][1] < B[j][1]){
i++;
}else if(A[i][1] == B[j][1]){
i++;
j++;
}else{
j++;
}
}
}
return res;
}
};