[LeetCode] 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.

Example 1:

Input: intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
Output: [[0,1],[6,7]]

Example 2:

Input: intervals = [[0,5]], toBeRemoved = [2,3]
Output: [[0,2],[3,5]]

Example 3:

Input: intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]
Output: [[-5,-4],[-3,-2],[4,5],[8,9]]

Constraints:

  • 1 <= intervals.length <= 104
  • -109 <= ai < bi <= 109

删除区间。

实数集合可以表示为若干不相交区间的并集,其中每个区间的形式为 [a, b)(左闭右开),表示满足 a <= x < b 的所有实数  x 的集合。如果某个区间 [a, b) 中包含实数 x ,则称实数 x 在集合中。

给你一个 有序的 不相交区间列表 intervals 。intervals 表示一个实数集合,其中每一项 intervals[i] = [ai, bi] 都表示一个区间 [ai, bi) 。再给你一个要删除的区间 toBeRemoved 。

返回 一组实数,该实数表示intervals 中 删除 了 toBeRemoved 的部分 。换句话说,返回实数集合,并满足集合中的每个实数 x 都在 intervals 中,但不在 toBeRemoved 中。你的答案应该是一个如上所述的 有序的 不相连的间隔列表 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-interval
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这也是属于扫描线一类的题目。思路也比较直接,遍历 input 数组,跟需要去掉的区间 toBeRemoved 没有重叠的子区间就直接加入结果集。如果跟 toBeRemoved 有重叠的部分,则比较两者的左边界和右边界来得出需要去掉的区间是什么。

时间O(n)

空间O(n) - output list

Java实现

 1 class Solution {
 2     public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         for (int[] i : intervals) {
 5             // no overlap
 6             if (i[1] <= toBeRemoved[0] || i[0] >= toBeRemoved[1]) {
 7                 res.add(Arrays.asList(i[0], i[1]));
 8             }
 9             // i[1] > toBeRemoved[0] && i[0] < toBeRemoved[1]
10             else {
11                 // left end no overlap
12                 if (i[0] < toBeRemoved[0]) {
13                     res.add(Arrays.asList(i[0], toBeRemoved[0]));
14                 }
15                 // right end no overlap
16                 if (i[1] > toBeRemoved[1]) {
17                     res.add(Arrays.asList(toBeRemoved[1], i[1]));
18                 }
19             }
20         }
21         return res;
22     }
23 }

 

扫描线相关题目

LeetCode 题目总结

 
posted @ 2020-08-05 02:43  CNoodle  阅读(690)  评论(2编辑  收藏  举报