56. 合并区间

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        if(!intervals.size()) return intervals;
        sort(intervals.begin(), intervals.end());
        int k = 0;
        for(int i = 1; i < intervals.size(); i++){
            if(intervals[i][0] > intervals[k][1])
                intervals[++k][0] = intervals[i][0];
            intervals[k][1] = max(intervals[k][1], intervals[i][1]);
        }
        intervals.resize(k+1);
        return intervals;
    }
};

495. 提莫攻击

class Solution {
public:
    int findPoisonedDuration(vector<int>& timeSeries, int duration) {
        if(!timeSeries.size() || !duration) return 0;
        int res = 0;
        for(int i = 1; i < timeSeries.size(); i++)
            res += min(timeSeries[i]-timeSeries[i-1], duration);
        res += duration;
        return res;
    }
};

763. 划分字母区间

class Solution {
public:
    vector<int> partitionLabels(string s) {
        vector<int> alphabet(26, 0), res;
        int count = 0, l = 0; // count记录数量
        for(auto c:s)
            alphabet[c-'a']++;
        for(int i = 0; i < s.size(); i++){
            if(alphabet[s[i]-'a']){
                count += alphabet[s[i]-'a'];
                alphabet[s[i]-'a'] = 0;
            }
            count--;

            if(!alphabet[s[i]-'a'] && !count){
                res.push_back(i-l+1);
                l = i+1;
            }
        }
        return res;
    }
};
class Solution {
public:
    vector<int> partitionLabels(string s) {
        vector<int> last(26, 0), res;
        int l = 0, r = 0; // 左右指针
        for(int i = 0; i < s.size(); i++) // 记录每个字母最后出现的位置
            last[s[i]-'a'] = i;
        for(int i = 0; i < s.size(); i++){
            r = max(r, last[s[i]-'a']); 
            if(r == i){
                res.push_back(r-l+1);
                l = i+1;
            }
        }
        return res;
    }
};

986. 区间列表的交集

class Solution {
public:
    vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
        vector<vector<int>> res;
        int l, r;
        for(int i = 0, j = 0; i < A.size() && j < B.size();){
            l = max(A[i][0], B[j][0]);
            r = min(A[i][1], B[j][1]);
            if(l <= r)
                res.push_back({l, r});
            if(r == A[i][1]) i++;
            else j++;
        }
        return res;
    }
};

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值