代码随想录算法训练营第三十六天 | 435. 无重叠区间、763. 划分字母区间、56. 合并区间

57 阅读1分钟

代码随想录算法训练营第三十六天 | 435. 无重叠区间、763. 划分字母区间、56. 合并区间

435. 无重叠区间

题目链接:435. 无重叠区间

  • 区间调度问题
  • 按照右区间排序
  • 局部最优:从左往右依次选取右区间最小的区间,这样能够得到更大的空间给别的区间
  • 找到不重叠的区间之后答案需要总区间数减去不重叠区间

763. 划分字母区间

题目链接:763. 划分字母区间

  • 存储每个字符出现的最后一个位置
  • 在遍历过程中找到字母的最远区间

56. 合并区间

题目链接:56. 合并区间

  • 按照开始位置排序区间,不断地更新右边界
  • 如果遍历到的区间的左边界大于当前右边界,说明没有重叠,需要加入结果集
  •  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);
             vector<vector<int>> res;
             res.push_back(intervals[0]);
     ​
             for (int i = 1; i < intervals.size(); i++) {
                 vector<int> &lastInterval = res.back();
                 auto curr = intervals[i];
                 int end = lastInterval[1];
                 if(curr[0] > end) {
                     res.push_back(curr);
                 } else {
                     lastInterval[1] = max(curr[1], lastInterval[1]);
                 }
             }
             return res;
         }
     };
     ​