在 C++ 中插入区间

c++server side programmingprogramming更新于 2025/6/25 22:22:17

假设我们有一组不重叠的区间;我们需要在这些区间中插入一个新的区间。如有必要,我们可以合并它们。因此,如果输入为 − [[1,4],[6,9]],而新区间为 [2,5],则输出将为 [[1,5],[6,9]]。

为了解决这个问题,我们将按照以下步骤 −

  • 在前一个区间列表的末尾插入新的区间

  • 根据区间的初始时间对区间列表进行排序,n := 区间数

  • 创建一个名为 ans 的数组,将第一个区间插入 ans 中

  • index := 1

  • while index < n,

    • last := ans 的大小 – 1

    • 如果 ans[last, 0] 和 ans[last, 1] 中的最大值 < intervals[index, 0] 和 intervals[index, 1] 中的最小值,则将 intervals[index] 插入 ans

    • 否则

      • 设置 ans[last, 0] := ans [last, 0] 和 intervals[index, 0] 中的最小值

      • 设置 ans[last, 1] := ans [last, 1] 和 intervals[index, 1] 中的最小值

    • 将 index 增加 1

  • return ans

示例

让我们看下面的实现,以便更好地理解 −

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   static bool cmp(vector <int> a, vector <int> b){
      return a[0]<b[0];
   }
   vector<vector <int>>insert(vector<vector <int> >& intervals, vector <int>& newInterval) {
      intervals.push_back(newInterval);
      sort(intervals.begin(),intervals.end(),cmp);
      int n = intervals.size();
      vector <vector <int>> ans;
      ans.push_back(intervals[0]);
      int index = 1;
      bool done = false;
      while(index<n){
         int last = ans.size()-1;
         if(max(ans[last][0],ans[last][1])<min(intervals[index][0],intervals[i ndex][1])){
            ans.push_back(intervals[index]);
         } else {
            ans[last][0] = min(ans[last][0],intervals[index][0]);
            ans[last][1] = max(ans[last][1],intervals[index][1]);
         }
         index++;
      }
      return ans;
   }
};
main(){
   vector<vector<int>> v = {{1,4},{6,9}};
   vector<int> v1 = {2,5};
   Solution ob;
   print_vector(ob.insert(v, v1));
}

输入

[[1,4],[6,9]]
[2,5]

输出

[[1, 5, ],[6, 9, ],]

相关文章