贪心一直做的很难受,前两天在忙面试,进度有点拉下了
python
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda x: (x[0],x[1]-x[0]))
result = 1
for i in range(1, len(intervals)):
if intervals[i][0] >= intervals[i - 1][1]:
result += 1
else:
intervals[i][1] = min(intervals[i - 1][1], intervals[i][1]) # 更新重叠气球最小右边界
return len(intervals)-result
python
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last_occurrence = {} # 存储每个字符最后出现的位置
for i, ch in enumerate(s):
last_occurrence[ch] = i
result = []
start = 0
end = 0
for i, ch in enumerate(s):
end = max(end, last_occurrence[ch]) # 找到当前字符出现的最远位置
if i == end: # 如果当前位置是最远位置,表示可以分割出一个区间
result.append(end - start + 1)
start = i + 1
return result
这道题一开始的思路就是,一个for循环,觉得只需要做一次
python
interval = intervals[i]
last_interval = intervals[i-1]
if interval[0] <= last_interval[1]:
last_interval[1] = max(interval[1],last_interval[1])
最后再把修改过的interval删除掉就可以了,但是没考虑到
[[1,4],[0,2],[3,5]]
[[0,4],[3,5]]
只遍历一遍的话,还是会有重复的。
看了题解发现是不能只跟intervals里的元素比较,应该跟结果集里的元素去进行比较。
python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key = lambda x : x[0])
a = [intervals[0]]
for i in range(1,len(intervals)):
if a[-1][1] >= intervals[i][0]:
a[-1][1] = max(a[-1][1],intervals[i][1])
else:
a.append(intervals[i])
return a