1272. Remove Interval
Given a sorted list of disjoint intervals
, each interval intervals[i] = [a, b]
represents the set of real numbers x
such that a <= x < b
.
We remove the intersections between any interval in intervals
and the interval toBeRemoved
.
Return a sorted list of intervals
after all such removals.
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]]
Constraints:
1 <= intervals.length <= 10^4
-10^9 <= intervals[i][0] < intervals[i][1] <= 10^9
class Solution { public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) { List<List<Integer>> ans = new ArrayList<>(); for (int[] i : intervals) { if (i[1] <= toBeRemoved[0] || i[0] >= toBeRemoved[1]) { // no overlap. ans.add(Arrays.asList(i[0], i[1])); }else { // i[1] > toBeRemoved[0] && i[0] < toBeRemoved[1]. if(i[0] < toBeRemoved[0]) // left end no overlap. ans.add(Arrays.asList(i[0], toBeRemoved[0])); if (i[1] > toBeRemoved[1]) // right end no overlap. ans.add(Arrays.asList(toBeRemoved[1], i[1])); } } return ans; } }
有点像merge interval,但是更简单。
对每个数组有三种情况,
1. 不相交(说明没有要删除的),把数组添加进list
2. 左边相交
3. 右边相交
后两种判断后添加即可。