Skip to content

Instantly share code, notes, and snippets.

@liyunrui
Created April 30, 2020 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyunrui/b2298126b128b7b764a0ae001596dbf1 to your computer and use it in GitHub Desktop.
Save liyunrui/b2298126b128b7b764a0ae001596dbf1 to your computer and use it in GitHub Desktop.
leetcode-greedy
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
"""
Greedy problem because of pattern: "Find minimum or maximum number of something to do something"
T: O(nlogn)
S: O(1). No extra space is used.
Reference: https://leetcode.com/problems/non-overlapping-intervals/discuss/276056/Python-Greedy-Interval-Scheduling
"""
ending_time, ans = float('-inf'), 0 # the earliest end time
for i in sorted(intervals, key=lambda x: x[1]):
start_time = i[0]
if start_time >= ending_time:
# always pick up the current earliest ending time
ending_time = i[1]
else:
ans += 1
return ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment