今天的题目都与重叠区间有关。第一题是无重叠区间https://leetcode.cn/problems/non-overlapping-intervals/description/,与昨天用箭射气球的逻辑相同,按左边界排序,找出重叠区间数量即可。
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) {
sort(intervals.begin(), intervals.end(), cmp);
int result = 0;
for (int i = 1; i < intervals.size(); i++){
if (intervals[i - 1][1] <= intervals[i][0]);
else {
result++;
intervals[i][1] = min (intervals[i - 1][1], intervals[i][1]);
}
}
return result;
}
};
第二题是划分字母区间https://leetcode.cn/problems/partition-labels/submissions/503106369/,该题是哈希与贪心的综合,首先用哈希方法统计字符串中个字母的最远出现位置,在向后遍历过程中不断记录不同字母的最远位置,到达最远位置时记录结果,更新区间左端位置,再次向后遍历。
class Solution {
public:
vector<int> partitionLabels(string s) {
int hash[26] = {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 (right == i){
result.push_back(right - left + 1);
left = right + 1;
}
}
return result;
}
};
第三题是合并区间https://leetcode.cn/problems/merge-intervals/description/,先判断是否重叠,若重叠,更新右边界,若不重叠,直接讲区间加入结果集中。
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) {
if (intervals.size() == 0) return intervals;
sort(intervals.begin(), intervals.end(), cmp);
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.back()[1] = max(result.back()[1], intervals[i][1]);
}
else result.push_back(intervals[i]);
}
return result;
}
};
100题目标达成,给自己留个纪念哈哈😄加油