Leetcode # 435. Non-overlapping Intervals
- 2023.07.20
- LeetCode
https://leetcode.com/problems/non-overlapping-intervals
First Solution
Time Complexity: O(len(intervals))
Space Complexity: O(len(intervals))
(The input and output generally do not count towards the space complexity.)
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
starts = collections.defaultdict(list)
for i in intervals:
starts[i[0]].append(i[1])
removed_n = sum([len(starts[s]) - 1 for s in starts])
left_intervals = sorted([[s, min(starts[s])]for s in starts])
i = 0
while i < len(left_intervals) - 1:
if left_intervals[i][1] > left_intervals[i + 1][0]:
if left_intervals[i][1] >= left_intervals[i + 1][1]:
left_intervals.pop(i)
else:
left_intervals.pop(i + 1)
removed_n += 1
else:
i += 1
return removed_n
Refined Solution
第一版的演算法主要有兩個部分
- if starti == startj and endi <= endj
⇒ 刪除 intervals[j] - if starti > endj ⇒ 刪除 intervals[argmaxk=i, j(endk)]
可以總結為:
if intervals[i] and intervals[j] overlapped
⇒ 刪除 intervals[argmaxk=i, j(endk)]
Time Complexity: O(len(intervals))
Space Complexity: O(len(intervals))
(The input and output generally do not count towards the space complexity.)
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
_intervals = sorted(intervals, key = lambda x:x[1])
removed_n = 0
previous_end = -inf
for s, e in _intervals:
if s >= previous_end:
previous_end = e
else:
removed_n += 1
return removed_n
Last Updated on 2023/08/16 by A1go