C++で異なるサイズのk個のソートされた配列をマージします
異なるk個のソートされた配列があるとします。これらの配列をマージして、ソートされた結果を表示する必要があります。
したがって、入力がk =3のようで、配列が{2、4}、{3、5、7}、{1、10、11、12}の場合、出力は1 2 3 4 5 71011になります。 12
これを解決するには、次の手順に従います-
- 最初の要素が整数で、2番目の要素が別の整数のペアであるペアの1つのタイプを定義し、ppiという名前を付けます。
- 配列操作を定義する
- 1つの優先キューを定義するq
- iを初期化する場合:=0、i
- (arr [i、0]、{i、0})をqに挿入
- を実行します。
- current_element:=qの最上位要素
- qから要素を削除
- i:=current_elementから2番目の要素
- j:=current_elementから3番目の要素
- opの最後にcurrent_elementの最初の要素を挿入します
- j + 1
- (arr [i、j + 1]、{i、j + 1})をqに挿入
例
理解を深めるために、次の実装を見てみましょう-
#include <bits/stdc++.h>
using namespace std;
#define ppi pair<int,pair<int,int>>
vector<int> merge(vector<vector<int> > arr){
vector<int> op;
priority_queue<ppi, vector<ppi>, greater<ppi> > queue;
for (int i = 0; i < arr.size(); i++)
queue.push({ arr[i][0], { i, 0 } });
while (queue.empty() == false) {
ppi current_element = queue.top();
queue.pop();
int i = current_element.second.first;
int j = current_element.second.second;
op.push_back(current_element.first);
if (j + 1 < arr[i].size())
queue.push({ arr[i][j + 1], { i, j + 1 } });
}
return op;
}
int main(){
vector<vector<int> > arr{ { 2,4}, { 3,5,7 }, { 1, 10, 11, 12 } };
vector<int> output = merge(arr);
for(int i = 0; i<output.size(); i++)
cout << output[i] << " ";
} 入力
{{ 2,4}, { 3,5,7 }, { 1, 10, 11, 12 }} 出力
1 2 3 4 5 7 10 11 12
-
C /C++の多次元配列
C / C ++では、多次元配列は簡単な言葉で配列の配列として定義されます。多次元配列では、データは表形式で(行の主要な順序で)格納されます。次の図は、次元が3 x 3x3の多次元配列のメモリ割り当て戦略を示しています。 アルゴリズム Begin Declare dimension of the array. Dynamic allocate 2D array a[][] using new. Fill the array with the elements. Print the ar
-
Javaでk個のソートされた配列をマージ
「n」個の配列が与えられます。たとえば、整数型のarr1 []、arr2 []、およびarr3[]の3つの配列を使用するとします。タスクは、結果の配列が実行時にのみソートされるように、指定されたすべての整数配列をマージすることです。 例を挙げて理解しましょう 入力 − Int a [] ={21,22,23,24}; int b [] ={28,31,35} 出力 −int result []={21,22,23,24,28,31,35}。 説明 −配列要素は、追加される前に比較され、結果の配列内の適切な位置に従って追加されます。 入力 − int a [] ={