代码随想录算法训练营第三十六天|435. 无重叠区间、763.划分字母区间、56. 合并区间

435. 无重叠区间

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
文档讲解:代码随想录
视频讲解:贪心算法,依然是判断重叠区间 | LeetCode:435.无重叠区间_哔哩哔哩_bilibili

C++代码:

class Solution {
public:
    static bool cmp (const vector& a, const vector& b) {
        return a[1] < b[1];
    }
    int eraseOverlapIntervals(vector>& intervals) {
        if (intervals.size() == 0) return 0;
        sort(intervals.begin(), intervals.end(), cmp);
        int count = 1;
        int end = intervals[0][1];
        for (int i = 1; i < intervals.size(); i++) {
            if (end <= intervals[i][0]) {
                end = intervals[i][1];
                count++;
            }
        }
        return intervals.size() - count;
    }
};

763.划分字母区间

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
文档讲解:代码随想录
视频讲解:贪心算法,寻找最远的出现位置! LeetCode:763.划分字母区间_哔哩哔哩_bilibili

C++代码:

class Solution {
public:
    vector partitionLabels(string s) {
        int hash[27] = {0};
        for (int i = 0; i < s.size(); i++) {
            hash[s[i] - 'a'] = i;
        }
        vector result;
        int left = 0;
        int right = 0;
        for (int i = 0; i < s.size(); i++) {
            right = max(right, hash[s[i] - 'a']);
            if (i == right) {
                result.push_back(right - left + 1);
                left = i + 1;
            }
        }
        return result;
    }
};

56. 合并区间

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
文档讲解:代码随想录
视频讲解:贪心算法,合并区间有细节!LeetCode:56.合并区间_哔哩哔哩_bilibili

C++代码:

class Solution {
public:
    vector> merge(vector>& intervals) {
        vector> result;
        if (intervals.size() == 0) return result;
        sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){return a[0] < b[0];});

        result.push_back(intervals[0]); 

        for (int i = 1; i < intervals.size(); i++) {
            if (result.back()[1] >= intervals[i][0]) {
                result.back()[1] = max(result.back()[1], intervals[i][1]); 
            } else {
                result.push_back(intervals[i]);
            }
        }
        return result;
    }
};

你可能感兴趣的:(代码随想录算法训练营,算法)