无重叠区间
将右边界排序,统计非重叠区间个数
cpp
class Solution {
static bool cmp(vector<int>& a, vector<int>& b){
return a[1] < b[1];
}
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int res = 1;
sort(intervals.begin(), intervals.end(), cmp);
int end = intervals[0][1];
for(int i = 1; i < intervals.size(); i++){
if(intervals[i][0] >= end){
res++;
end = intervals[i][1];
}
}
return intervals.size() - res;
}
};
将左边界排序,统计重叠区间个数
cpp
class Solution {
static bool cmp(vector<int>& a, vector<int>& b){
return a[0] < b[0];
}
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int res = 0;
sort(intervals.begin(), intervals.end(), cmp);
for(int i = 1; i < intervals.size(); i++){
if(intervals[i][0] < intervals[i-1][1]){
res++;
intervals[i][1] = min(intervals[i][1], intervals[i-1][1]);
}
}
return res;
}
};
划分字母区间
cpp
class Solution {
public:
vector<int> partitionLabels(string s) {
int hash[26] = {0};
vector<int> result;
for(int i = 0; i < s.size(); i++){
hash[s[i] - 'a'] = i;
}
int right = 0;
int left = 0;
for(int i = 0; i < s.size(); i++){
right = max(hash[s[i] - 'a'], right);
if(i == right){
result.push_back(right - left + 1);
left = i + 1;
}
}
return result;
}
};
合并区间
cpp
class Solution {
static bool cmp(vector<int>& a, vector<int>& b){
return a[0] < b[0];
}
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size() == 1) return intervals;
vector<vector<int>> result;
if(intervals.size() == 0) return result;
sort(intervals.begin(), intervals.end(), cmp);
int right = intervals[0][1];
int left = intervals[0][0];
for(int i = 1; i < intervals.size(); i++){
if(intervals[i][0] <= intervals[i-1][1]){ //重叠了
right = max(intervals[i][1], intervals[i-1][1]);
intervals[i][1] = right;
}
else{
result.push_back({left, right});
right = intervals[i][1];
left = intervals[i][0];
}
}
result.push_back({left, right});
return result;
}
};