代码随想录day36|● 435. 无重叠区间 ● 763.划分字母区间 ● 56. 合并区间

435. 无重叠区间

基本就是上一题,并不是真的删除,而是更新右端点,最小的右端点,模拟删除两个重叠区间之间较长的那个。

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

763.划分字母区间

  • 开始思路卡住了,没想到要先遍历一遍,hash映射记录最远位置
class Solution {
public:
    vector<int> partitionLabels(string s) {
        int hash[27]={0};
        for (int i = 0; i < s.size(); ++i) {
            hash[s[i]-'a']=i;
        }
        int left=0,right=0;
        vector<int> result;
        for (int i = 0; i < s.size(); ++i) {
            right = max(hash[s[i]-'a'],right);
            if (right == i) {
                result.push_back(right-left+1);
                left = right+1;
            }
        }
        return result;
    }
};

56. 合并区间

  • 独立写出
class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        if(intervals.size()<=1) return intervals;
        sort(intervals.begin(),intervals.end(),
             [](vector<int>& a, vector<int>&b){return a[0]<b[0];});
        vector<int> tmp = {INT_MAX, INT_MAX};
        intervals.push_back(tmp);
        vector<vector<int>> result;
       // result.resize(intervals.size());
        for (int i = 1; i < intervals.size(); ++i) {
            if(intervals[i][0] <= intervals[i-1][1]) {
                intervals[i][1] = max(intervals[i-1][1],intervals[i][1]);
                intervals[i][0] = intervals[i-1][0];
            } else result.push_back(intervals[i-1]);
        }
        return result;
    }
};

你可能感兴趣的:(哈希算法,贪心算法,leetcode,c++)