435.重叠区间
- 左边界或者右边界对齐
- 明确result记录的是重叠区间所以初始化为0、如果记录的是非重叠区间,则需要初始化为1
- 判断准则上一个的右边界和当前的左边界是否重叠,如果重叠,更新当前的右边界
class Solution {
public:
static bool cmp(const vector<int>& a,const vector<int>& b){
return a[0]<b[0];
}
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int result=0;
sort(intervals.begin(),intervals.end(),cmp);
for(int i=1;i<intervals.size();i++){
if(intervals[i-1][1]>intervals[i][0]){
intervals[i][1]=min(intervals[i-1][1],intervals[i][1]);
result++;
}
}
return result;
}
};
763.划分字母区间
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> result;
vector<int> hash(27,0);
int left=0;
int right=0;
for(int i=0;i<s.size();i++){
hash[s[i]-'a']=i;
}
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 {
public:
static bool cmp(const vector<int>& a,const vector<int>& b){
return a[0]<b[0];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> result;
sort(intervals.begin(),intervals.end(),cmp);
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;
}
};