用 C++ 插入区间
假设我们有一组非重叠区间。我们必须插入一个新区间到这些区间。如果需要,可以合并。因此,如果输入如下 − [[1,4],[6,9]],新区间为 [2,5],则输出为 [[1,5],[6,9]]。
要解决此问题,我们将按照以下步骤进行操作 −
在先前区间列表的末尾插入新区间
根据区间的初始时间对区间列表进行排序,n := 区间数
创建一个名为 ans 的数组,将第一个区间插入到 ans 中
index := 1
当 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
返回 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, ],]
广告
数据结构
网络技术
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP