Leetcode| 435. 无重叠区间、763. 划分字母区间、56. 合并区间 Day36

435. Non-overlapping Intervals

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        # 按右边界从小到大排序
        intervals.sort(key = lambda x: x[1])

        end = intervals[0][1]   # 区间的分割点
        count = 1   # 记录非重叠区间的数量
        for i in range(1, len(intervals)):
            if intervals[i][0] >= end:
                count += 1
                end = intervals[i][1]
                
        return len(intervals) - count

763. Partition Labels

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        hash = [0] * 26
        for i in range(len(s)):
            hash[ord(s[i]) - ord('a')] = i   # 统计每一个字符最后出现的位置

        res = []
        left = 0
        right = 0
        for i in range(len(s)):
            right = max(right, hash[ord(s[i]) - ord('a')])   # 找到字符出现的最远边界
            if right == i:
                res.append(right - left + 1)
                left = i + 1

        return res

56. Merge Intervals

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        # 按左边界排序
        intervals.sort(key = lambda x: x[0])
        res = []
        res.append(intervals[0])
        for i in range(1, len(intervals)):
            last = res[-1]
            if intervals[i][0] <= last[1]:  # 当前左边界 <= 前一个右边界
                res[-1] = [last[0], max(last[1], intervals[i][1])]
            else:
                res.append(intervals[i])    # 与前一个无重叠
        
        return res

你可能感兴趣的:(算法,leetcode,算法,职场和发展)