중복되지 않는 간격 집합이 있다고 가정합니다. 간격에 새 간격을 삽입해야 합니다. 필요한 경우 병합할 수 있습니다. 따라서 입력이 − [[1,4],[6,9]]이고 새 간격이 [2,5]이면 출력은 [[1,5],[6,9]]가 됩니다.
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
이전 간격 목록 끝에 새 간격 삽입
-
간격의 초기 시간을 기준으로 간격 목록을 정렬합니다. n :=간격의 수
-
ans라는 배열 하나를 만들고 첫 번째 간격을 ans
에 삽입합니다. -
인덱스 :=1
-
동안 인덱스
-
마지막 :=ans의 크기 – 1
-
ans[last, 0]의 최대값과 ans[last, 1] <간격의 최소값[index, 0], interval[index, 1]이면 ans에 간격[index]을 삽입합니다.
-
그렇지 않으면
-
set ans[last, 0] :=ans의 min [last, 0], 간격[index, 0]
-
set ans[last, 1] :=ans의 최소값 [last, 1], 간격[index, 1]
-
-
인덱스 1 증가
-
-
반환
예
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#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, ],]