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.
(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].)
Analysis:
输入是一对一对的区间组,有两个,求他们每对区间的交集。
Solution1:
自己的思路,很直接的思路
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> ret;
if (A.size() == 0 || B.size() == 0)
return ret;
for (int i = 0; i < A.size(); i ++) {
vector<int> cur;
for (int j = 0; j < B.size(); j ++) {
if ((A[i][0] > B[j][1]) || (A[i][1] < B[j][0])) {
continue;
}
if ((A[i][0] >= B[j][0] && A[i][0] <= B[j][1]) && (A[i][0] <= B[j][1] && B[j][1] <= A[i][1])) {
cur.push_back(A[i][0]);
cur.push_back(B[j][1]);
} else if (A[i][0] < B[j][0] && B[j][1] < A[i][1]) {
cur.push_back(B[j][0]);
cur.push_back(B[j][1]);
} else if (B[j][0] < A[i][0] && A[i][1] < B[j][1]) {
cur.push_back(A[i][0]);
cur.push_back(A[i][1]);
} else if ((A[i][0] <= B[j][0] && B[j][0] <= A[i][1]) && (A[i][1] >= B[j][0] && A[i][1] <= B[j][1])) {
cur.push_back(B[j][0]);
cur.push_back(A[i][1]);
}
// 开始这里写到外层循环,出错
if (!cur.empty()) {
ret.push_back(cur);
}
cur.clear();
}
}
return ret;
}
};
Solution2:
参考别人,很巧妙的方法
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> ret;
if (A.size() == 0 || B.size() == 0)
return ret;
for (int i = 0; i < A.size(); i ++) {
vector<int> cur;
cur.reserve(2);
for (int j = 0; j < B.size(); j ++) {
int low = max(A[i][0], B[j][0]);
int high = min(A[i][1], B[j][1]);
if (low <= high) {
cur.push_back(low);
cur.push_back(high);
}
if (!cur.empty()) {
ret.push_back(cur);
}
cur.clear();
}
}
return ret;
}
};