代码随想录算法训练营Day36|435. 无重叠区间、763.划分字母区间、56. 合并区间
435. 无重叠区间
题目链接:435. 无重叠区间
文档链接:435. 无重叠区间
视频链接:贪心算法,依然是判断重叠区间 | LeetCode:435.无重叠区间
C++实现
class Solution {
private:
static bool cmp(const vector<int>& a, const vector<int>& b) {
return a[0] < b[0];
}
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if (intervals.size() == 0)
return 0;
sort(intervals.begin(), intervals.end(), cmp);
int count = 0;
int right = intervals[0][1];
for (int i = 1; i < intervals.size(); i++) {
if (intervals[i][0] < right) {
if (intervals[i][1] < right) {
right = intervals[i][1];
}
count++;
} else
right = intervals[i][1];
}
return count;
}
};
763.划分字母区间
题目链接:763.划分字母区间
文档链接:763.划分字母区间
视频链接:贪心算法,寻找最远的出现位置! LeetCode:763.划分字母区间
C++实现
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++) {
int cover = hash[s[i] - 'a'];
if (cover > right)
right = cover;
if (i == right) {
result.push_back(right - left + 1);
left = i + 1;
}
}
return result;
}
};
56. 合并区间
题目链接:56. 合并区间
文档链接:56. 合并区间
视频链接:贪心算法,合并区间有细节!LeetCode:56.合并区间
C++实现
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>> result;
if (intervals.size() == 0)
return result;
sort(intervals.begin(), intervals.end(), cmp);
result.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
if (intervals[i][0] <= result.back()[1]) {
if (result.back()[1] < intervals[i][1]) {
result.back()[1] = intervals[i][1];
}
} else {
result.push_back(intervals[i]);
}
}
return result;
}
};
原文地址:https://blog.csdn.net/Magical_Jasen/article/details/136414526
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!