435. 无重叠区间
https://leetcode.cn/problems/non-overlapping-intervals/
左对齐:
class Solution {
public:
static bool myCmp(vector<int>& a, vector<int>& b) {
return a[0] < b[0];
}
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if (intervals.empty()) return 0;
int result = 0;
sort(intervals.begin(), intervals.end(), myCmp);
for (int i = 1; i < intervals.size(); i++) {
if(intervals[i - 1][1] > intervals[i][0]) {
result++;
intervals[i][1] = min(intervals[i - 1][1], intervals[i][1]);
}
}
return result;
}
};
右对齐:
class Solution {
public:
static bool myCmp(vector<int>& a, vector<int>& b) {
return a[1] < b[1];
}
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int result = 0;
sort(intervals.begin(), intervals.end(), myCmp);
for (int i = 1; i < intervals.size(); i++) {
if(intervals[i - 1][1] > intervals[i][0]) {
result++;
intervals[i] = intervals[i - 1];
}
}
return result;
}
};
763.划分字母区间
https://leetcode.cn/problems/partition-labels/
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> result;
unordered_map<char, int> map;
for (int i = 0; i < s.length(); i++) {
map[s[i]] = i;
}
int left = 0, right = 0;
for (int i = 0; i < s.length(); i++) {
right = max(right, map[s[i]]);
if (right == i) {
result.push_back(right - left + 1);
left = i + 1;
}
}
return result;
}
};
56. 合并区间
https://leetcode.cn/problems/merge-intervals/
class Solution {
public:
static bool myCmp(vector<int> &a, vector<int> &b) {
return a[0] < b[0];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), myCmp);
vector<vector<int>> result;
result.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
if (result.back()[1] < intervals[i][0]) {
result.push_back(intervals[i]);
}
else {
result.back()[1] = max(result.back()[1], intervals[i][1]);
}
}
return result;
}
};