【leetcode】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(object):
    def removeInterval(self, intervals, toBeRemoved):
        """
        :type intervals: List[List[int]]
        :type toBeRemoved: List[int]
        :rtype: List[List[int]]
        """
        res = []
        for start,end in intervals:
            if end <= toBeRemoved[0] or start > toBeRemoved[1]:
                res.append([start,end])
            elif start == toBeRemoved[0] and end == toBeRemoved[1]:
                continue
            elif start == toBeRemoved[0] and end < toBeRemoved[1]:
                continue
            elif start == toBeRemoved[0] and end > toBeRemoved[1]:
                res.append([toBeRemoved[1],end])
            elif start >= toBeRemoved[0] and end == toBeRemoved[1]:
                continue
            elif start >= toBeRemoved[0] and end <= toBeRemoved[1]:
                continue
            elif start >= toBeRemoved[0] and end > toBeRemoved[1]:
                res.append([toBeRemoved[1],end])
            elif start < toBeRemoved[0] and end == toBeRemoved[1]:
                res.append([start,toBeRemoved[0]])
            elif start < toBeRemoved[0] and end > toBeRemoved[1]:
                res.append([start,toBeRemoved[0]])
                res.append([toBeRemoved[1],end])
            elif start < toBeRemoved[0] and end < toBeRemoved[1]:
                res.append([start, toBeRemoved[0]])
        return res

 

posted @ 2019-12-03 19:24  seyjs  阅读(495)  评论(0编辑  收藏  举报