代码随想录算法训练营Day36 | 贪心算法(5/6) LeetCode 435. 无重叠区间 763.划分字母区间 56. 合并区间

贪心算法最后两天的练习了,题稍难了一些。

第一题

435. Non-overlapping Intervals

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

为了移除重叠部分,首先要做的就是排序,来让区间尽可能的重叠。然后寻找右边界的最小值。这和昨天的题 (LC452) 思路差不多,因此可以在它基础上稍作修改。

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        if not intervals:
            return 0
        
        intervals.sort(key=lambda x: 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

第二题

763. Partition Labels

You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

Return a list of integers representing the size of these parts.

第一次做这种题,没什么思路。

看了别人给出的解答:在遍历的过程中相当于是要找每一个字母的边界,如果找到之前遍历过的所有字母的最远边界,说明这个边界就是分割点了。此时前面出现过所有字母,最远也就到这个边界了。

可以分为如下两步:

  • 统计每一个字符最后出现的位置
  • 从头遍历字符,并更新字符的最远出现下标,如果找到字符最远出现位置下标和当前下标相等了,则找到了分割点
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

第三题

56. Merge Intervals

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

和前几道题差不多的思路,依然是先排序,然后看边界地方的重叠情况。

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        result = []
        if len(intervals) == 0:
            return result  
        intervals.sort(key=lambda x: x[0])  
        result.append(intervals[0])  
        for i in range(1, len(intervals)):
            if result[-1][1] >= intervals[i][0]:  
         
                result[-1][1] = max(result[-1][1], intervals[i][1])
            else:
                result.append(intervals[i])  

        return result

你可能感兴趣的:(LeetCode,算法,贪心算法,leetcode)