用 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