[LeetCode] 1272. Remove Interval

1272. Remove Interval

A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form [a, b). A real number x is in the set if one of its intervals [a, b) contains x (i.e. a <= x < b).

You are given a sorted list of disjoint intervals intervals representing a set of real numbers as described above, where intervals[i] = [ai, bi] represents the interval [ai, bi). You are also given another interval toBeRemoved.

Return the set of real numbers with the interval toBeRemoved removed from intervals. In other words, return the set of real numbers such that every x in the set is in intervals but not in toBeRemoved. Your answer should be a sorted list of disjoint intervals as described above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
vector<vector<int>> removeInterval(vector<vector<int>>& intervals, vector<int>& toBeRemoved) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> res;

for(int i = 0, j = 0; i < intervals.size(); i++) {
if(toBeRemoved[0] <= intervals[i][0] and intervals[i][1] <= toBeRemoved[1]) continue;
if(toBeRemoved[0] >= intervals[i][1] or toBeRemoved[1] <= intervals[i][0]) {
res.push_back(intervals[i]);
} else if(intervals[i][0] <= toBeRemoved[0] and toBeRemoved[1] <= intervals[i][1]) {
if(intervals[i][0] < toBeRemoved[0])
res.push_back({intervals[i][0], toBeRemoved[0]});
if(toBeRemoved[1] < intervals[i][1])
res.push_back({toBeRemoved[1], intervals[i][1]});
} else if(intervals[i][0] <= toBeRemoved[0]) {
res.push_back({intervals[i][0], toBeRemoved[0]});
} else {
res.push_back({toBeRemoved[1], intervals[i][1]});
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/08/PS/LeetCode/remove-interval/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.