贪心算法 part05 435. 无重叠区间 763. 划分字母区间 56. 合并区间
435. 无重叠区间
class Solution {
private:
bool static Compare(const vector<int>& a, const vector<int>& b){
return a[0] <b[0];
}
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(),intervals.end());
int result = 0;
for(int i = 0; i<intervals.size()-1;i++){
if(intervals[i][1]>intervals[i+1][0])
{
result++;
intervals[i+1][1] = min(intervals[i][1],intervals[i+1][1]);
}
}
return result;
}
};
763. 划分字母区间
class Solution {
public:
vector<int> partitionLabels(string S) {
int hash[26] = {0}; // i为字符,hash[i]为字符出现的最后位置
for (int i = 0; i < S.size(); i++) { // 统计每一个字符最后出现的位置
hash[S[i] - 'a'] = i;
}
vector<int> 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. 合并区间
class Solution {
private:
bool static Compare(const vector<int>& a, const vector<int>& b){
return a[0] <b[0];
}
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> result;
sort(intervals.begin(),intervals.end(),Compare);
result.push_back(intervals[0]);
for(int i =1 ; i<intervals.size();i++){
if(intervals[i][0]<=result.back()[1]){ //重叠
result.back()[1] = max(result.back()[1], intervals[i][1]);
}else result.push_back(intervals[i]);
}
return result;
}
};