Skip to content

Commit eb1d290

Browse files
authored
Create non-overlapping-intervals.py
1 parent 2a73fef commit eb1d290

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Time: O(nlogn)
2+
# Space: O(1)
3+
4+
# Given a collection of intervals, find the minimum number of intervals
5+
# you need to remove to make the rest of the intervals non-overlapping.
6+
#
7+
# Note:
8+
# You may assume the interval's end point is always bigger than its start point.
9+
# Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
10+
# Example 1:
11+
# Input: [ [1,2], [2,3], [3,4], [1,3] ]
12+
#
13+
# Output: 1
14+
#
15+
# Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
16+
# Example 2:
17+
# Input: [ [1,2], [1,2], [1,2] ]
18+
#
19+
# Output: 2
20+
#
21+
# Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
22+
# Example 3:
23+
# Input: [ [1,2], [2,3] ]
24+
#
25+
# Output: 0
26+
#
27+
# Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
28+
29+
# Definition for an interval.
30+
# class Interval(object):
31+
# def __init__(self, s=0, e=0):
32+
# self.start = s
33+
# self.end = e
34+
35+
class Solution(object):
36+
def eraseOverlapIntervals(self, intervals):
37+
"""
38+
:type intervals: List[Interval]
39+
:rtype: int
40+
"""
41+
intervals.sort(key=lambda interval: interval.start)
42+
result, prev = 0, 0
43+
for i in xrange(1, len(intervals)):
44+
if intervals[i].start < intervals[prev].end:
45+
if intervals[i].end < intervals[prev].end:
46+
prev = i
47+
result += 1
48+
else:
49+
prev = i
50+
return result

0 commit comments

Comments
 (0)