title: LEETCODE-DAY36
date: 2024-03-27 18:49:59
tags:
今日内容:435. 无重叠区间、763.划分字母区间、56. 合并区间
T1
思路类似DAY35 T3
python
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
j=0
for i in range(len(intervals)):
if i>0 and intervals[i][0]<intervals[i-1][1]:
#因为要使j尽可能小,故把较大的上界对应的区间remove
intervals[i][1]=min(intervals[i][1],intervals[i-1][1])
j+=1
return j
AC
T2
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
python
python
python
T3
python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
res=list()
intervals.sort()
for i in range(len(intervals)):
if i>0 and intervals[i][0]<=intervals[i-1][1]:
intervals[i][0]=intervals[i-1][0]
intervals[i][1]=max(intervals[i][1],intervals[i-1][1])
elif i>0 and intervals[i][0]>intervals[i-1][1]:
res.append(intervals[i-1])
return res
输入
intervals =
[[1,3],[2,6],[8,10],[15,18]]
输出
[[1,6],[8,10]]
预期结果
[[1,6],[8,10],[15,18]]
输入
intervals =
[[1,4],[4,5]]
输出
[]
预期结果
[[1,5]]
python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
res=list()
intervals.sort()
for i in range(len(intervals)):
if i>0 and intervals[i][0]<=intervals[i-1][1]:
intervals[i][0]=intervals[i-1][0]
intervals[i][1]=max(intervals[i][1],intervals[i-1][1])
elif i>0 and intervals[i][0]>intervals[i-1][1]:
res.append(intervals[i-1])
res.append(intervals[i])
return res
AC