435. 无重叠区间
class Solution {
private:
static bool cmp(vector<int>& a, vector<int>& b) {
return a[0] < b[0];
}
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if (intervals.size() == 1) return 0;
sort(intervals.begin(), intervals.end(), cmp);
int result = 0;
for (int i = 1; i < intervals.size(); i++) {
if (intervals[i][0] >= intervals[i - 1][1]) continue;
else {
result++;
intervals[i][1] = min(intervals[i][1], intervals[i - 1][1]);
}
}
return result;
}
};
和上一道弓箭问题是一样的。
763.划分字母区间
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;
}
vector<int> res;
int left = 0;
int right = 0;
for (int i = 0; i < s.size(); i++) {
right = max(right, hash[s[i] - 'a']);
if (i == right) {
res.push_back(right - left + 1);
left = i + 1;
}
}
return res;
}
};
56. 合并区间
class Solution {
private:
static bool cmp(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>> res;
if (intervals.size() == 0) return res;
sort(intervals.begin(), intervals.end(), cmp);
res.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
if (res.back()[1] >= intervals[i][0]) {
res.back()[1] = max(res.back()[1], intervals[i][1]);
}else {
res.push_back(intervals[i]);
}
}
return res;
}
};