class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: (x[0],x[1]))
count = 0
right = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0]>=right:
right = intervals[i][1]
else:
count+=1
right = min(right, intervals[i][1])
return count
这道题思路有点难想,如果能够想到使用position数组记录每个字母最后出现的位置后,题目及代码就比较好解了
class Solution:
def partitionLabels(self, s: str) -> List[int]:
res = []
pos = [0 for _ in range(len(s))]
storage = {}
for i in range(len(s)-1, -1, -1):
if s[i] not in storage.keys():
pos[i] = i
storage[s[i]] = i
else:
pos[i] = storage[s[i]]
last = pos[0]
start = 0
for i in range(len(pos)):
last = max(last, pos[i])
if last == i:
res.append(i-start+1)
start = i+1
return res
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x:x[0])
left = intervals[0][0]
right = intervals[0][1]
result = []
for i in range(1, len(intervals)):
if intervals[i][0]<=right:
right = max(right, intervals[i][1])
else:
result.append([left, right])
left = intervals[i][0]
right = intervals[i][1]
result.append([left, right])
return result