435. 无重叠区间
按照左边界排序,直接求重叠区间
class Solution:def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:if len(intervals) <= 1:return 0intervals.sort(key=lambda x: x[0])end = intervals[0][1]result = 0for i in range(1, len(intervals)):if intervals[i][0] < end:result += 1end = min(end, intervals[i][1]) # 一定要选择右边界较小的值else:end = intervals[i][1]return result
按照右边界排序,求得是不重叠区间
class Solution:def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:if len(intervals) <= 1:return 0intervals.sort(key=lambda x: x[1])end = intervals[0][1]result = 1 # result代表的是非重叠区间for i in range(1, len(intervals)):if intervals[i][0] >= end:result += 1end = intervals[i][1]return len(intervals) - result
763.划分字母区间
本题特别巧妙,没想出来
第一步遍历字符串,找到字符出现的最远距离
第二步遍历字符串,遍历过的字符的最远距离与当前索引相同的时候则可以划分
class Solution:def partitionLabels(self, s: str) -> List[int]:record = [0] * 27# 第一次遍历for i in range(len(s)):record[ord(s[i])-ord('a')] = i# 第二次遍历left = 0right = 0result = []for i in range(len(s)):right = max(right, record[ord(s[i])-ord('a')])if right == i:result.append(right-left+1)left = i + 1return result
56. 合并区间
代码写的比较冗余
class Solution:def merge(self, intervals: List[List[int]]) -> List[List[int]]:if len(intervals) <= 1:return intervals# 按照左边界排序intervals.sort(key=lambda x: x[0])left = intervals[0][0]right = intervals[0][1]result = []for interval in intervals:if interval[0] <= right:right = max(right, interval[1])else:result.append([left, right])left = interval[0]right = interval[1]result.append([left, right])return result
简洁的代码如下
class Solution:def merge(self, intervals: List[List[int]]) -> List[List[int]]:if len(intervals) <= 1:return intervals# 按照左边界排序intervals.sort(key=lambda x: x[0])result = [intervals[0]]for i in range(1, len(intervals)):if intervals[i][0] <= result[-1][1]:result[-1][1] = max(result[-1][1], intervals[i][1])else:result.append(intervals[i])return result