Informatica 编码轮问题
给定一个包含 n 个元素和一个整数 k 的数组。将数组划分为子数组,每个子数组包含k个元素。例如:
输入:arr[]={1, 32, 5, 6, 9, 3} 和 k=2
子数组将包含元素:
{132}、{56}、{93}。
现在将这些子数组排序为 {56}、{93}、{132}。将这些子数组合并在一起,并按排序顺序将它们显示为原始数组的元素
最终输出:arr[]={5, 6, 9, 3, 1, 32}
例子:
Input :
arr[]={1, 32, 5, 6, 9, 3}
k=2
Output :
arr[]={5, 6, 9, 3, 1, 32}
下面是上述思想的实现:
CPP
// C++ Program implementation of the above idea
#include
using namespace std;
void subarray_k(vector v, int n, int k)
{
int sum = 0;
int index;
string str = "";
vector > arr;
for (int i = 0; i < n - 1; i++)
{
index = i;
str = to_string(v[i]);
i++;
for (int j = 0; j < k - 1; j++)
{
// Conversion of array elements(integers) to
// string for easy concatenation
string temp = to_string(v[i]);
str += temp;
if (j != k - 2)
i++;
}
stringstream check(str);
int s = 0;
// Conversion of concatenated string to integer
check >> s;
arr.push_back(make_pair(s, index));
index++;
}
int u = 0;
// Sorting of array
sort(arr.begin(), arr.end());
vector v2;
for (int i = 0; i < (n / k); i++) {
u = 0;
int j = arr[i].second;
while (u < k) {
int a = v[j];
v2.push_back(a);
u++;
j++;
}
}
// print
for (int i = 0; i < n; i++)
{
cout << v2[i] << " ";
}
}
// Driver code
int main()
{
int n = 6;
vector v = { 1, 32, 5, 6, 9, 3 };
int k = 2;
// Function call
subarray_k(v, n, k);
return 0;
// This code is contributed by Siddhant Thapliyal
}
输出
5 6 9 3 1 32