986. Interval List Intersections
https://leetcode.com/problems/interval-list-intersections/description/
给定各自没有overlap且排好序的两组intervals,找出它俩之间的交集。类似merge sort,两个指针指向当前的Intervals,看它俩有没有交集,即检查最小的end和最大的start是否有交叉。检查后移动end小的指针往前走。
/*
* @lc app=leetcode id=986 lang=cpp
*
* [986] Interval List Intersections
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
const int M = A.size(), N = B.size();
int i = 0, j = 0;
vector<vector<int>> res;
while (i < M && j < N) {
const auto &a = A[i], &b = B[j];
const int s = max(a[0], b[0]), e = min(a[1], b[1]);
if (s <= e) {
res.push_back({s, e});
}
if (a[1] < b[1]) ++i;
else ++j;
}
return res;
}
};
// @lc code=end
Last updated
Was this helpful?