[LeetCode] Interval List Intersections

986. Interval List Intersections

You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

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 are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
vector<int> intersect(vector<int>& v1, vector<int>& v2) {
return {max(v1.front(), v2.front()), min(v1.back(), v2.back())};
}
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& f, vector<vector<int>>& s) {
vector<vector<int>> res;
int i(0), j(0);
while(i < f.size() && j < s.size()) {
vector<int> inter = intersect(f[i], s[j]);
if(inter.front() <= inter.back()) {
res.push_back(inter);
}
if(f[i].back() > s[j].back()) j++;
else i++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/19/PS/LeetCode/interval-list-intersections/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.