代码随想录刷题第三十六天
无重叠区间 (LC 435)
题目思路:
代码实现:
class Solution:def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:intervals.sort(key=lambda x: (x[0],x[1]))count = 0right = intervals[0][1]for i in range(1, len(intervals)):if intervals[i][0]>=right:right = intervals[i][1]else:count+=1right = min(right, intervals[i][1])return count
划分字母区间 (LC 763)
题目思路:
这道题思路有点难想,如果能够想到使用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] = istorage[s[i]] = ielse:pos[i] = storage[s[i]]last = pos[0]start = 0for i in range(len(pos)):last = max(last, pos[i])if last == i:res.append(i-start+1)start = i+1return res
合并区间 (LC 56)
题目思路:
代码实现:
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