C++で間隔を挿入
これを解決するには、次の手順に従います-
-
前の間隔リストの最後に新しい間隔を挿入します
-
間隔の初期時間に基づいて間隔リストを並べ替えます。n:=間隔の数
-
ansという1つの配列を作成し、最初の間隔をansに挿入します
-
インデックス:=1
-
インデックス
-
最後:=ansのサイズ– 1
-
最大のans[last、0]およびans [last、1] <最小のintervals[index、0]、intervals [index、1]の場合、intervals[index]をansに挿入します
-
それ以外の場合
-
set ans [last、0]:=min of ans [last、0]、intervals [index、0]
-
set ans [last、1]:=min of ans [last、1]、intervals [index、1]
-
-
インデックスを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, ],]
-
C++での型推論
型推論または推論とは、プログラミング言語での式のデータ型の自動検出を指します。これは、いくつかの強く静的に型付けされた言語に存在する機能です。 C ++では、autoキーワード(C ++ 11で追加)が自動型推定に使用されます。たとえば、ベクトルを反復処理するイテレータを作成する場合、その目的でautoを使用するだけです。 例 #include<iostream> #include<vector> using namespace std; int main() { vector<int> arr(10);
-
C++STLでの配置と挿入
emplace操作は、オブジェクトの不要なコピーを回避し、挿入操作よりも効率的に挿入を行います。挿入操作はオブジェクトへの参照を取ります。 アルゴリズム Begin Declare set. Use emplace() to insert pair. Use insert() to insert pair by using emplace(). Print the set. End サンプルコード #include<bits/stdc++.h> using namespace std; int main() { set<pai