435. 无重叠区间
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法,依然是判断重叠区间 | LeetCode:435.无重叠区间_哔哩哔哩_bilibili
状态:通过
代码实现:
class Solution {
public:
static bool cmp(vector<int>& a, vector<int>& b){
return a[0] < b[0];
}
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int cnt = 0;
sort(intervals.begin(), intervals.end(), cmp);
for(int i = 1; i < intervals.size(); i++){
if(intervals[i][0] < intervals[i - 1][1]){
cnt++;
intervals[i][1] = min(intervals[i - 1][1], intervals[i][1]);
}
}
return cnt;
}
};
763.划分字母区间
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法,寻找最远的出现位置! LeetCode:763.划分字母区间_哔哩哔哩_bilibili
状态:未通过
代码实现:
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> 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 = right + 1;
}
}
return result;
}
};
56. 合并区间
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法,合并区间有细节!LeetCode:56.合并区间_哔哩哔哩_bilibili
状态:通过
代码实现:
class Solution {
public:
static bool cmp(vector<int>& a, vector<int>& b){
return a[0] < b[0];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), cmp);
int left, right;
vector<vector<int>> result;
for(int i = 1; i < intervals.size(); i++){
if(intervals[i][0] <= intervals[i - 1][1]){
left = intervals[i - 1][0];
right = max(intervals[i - 1][1], intervals[i][1]);
intervals[i][0] = left;
intervals[i][1] = right;
}
else{
result.push_back(intervals[i - 1]);
}
}
result.push_back(intervals[intervals.size() - 1]);
return result;
}
};