【发布时间】:2020-08-12 02:58:21
【问题描述】:
请不要为极客提供极客解决方案,它不起作用
给定 k 个大小为 n 的排序数组,合并它们并打印排序后的输出。
int arr[][n] = {{2, 3, 5, 18},
{2, 8, 9, 17},
{1, 4, 7, 7, 8},
{1, 2, 3, 4},
{15, 17, 19}};
我试过这段代码,输出中的 0 太多
// C++ program to merge k sorted arrays of size n each.
#include<bits/stdc++.h>
using namespace std;
#define n 5
// A utility function to print array elements
void displayArray(int arr[], int size)
{
for (int i=0; i < size; i++)
cout << arr[i] << " ";
}
void mergeArrays(int arr[][n], int a, int output[])
{
int c=0;
for(int i=0; i<a; i++)
{
for(int j=0; j<n ;j++)
output[c++]=arr[i][j];
}
sort(output,output + n*a);
}
int main()
{
int arr[][n] = {{2, 3, 5, 18},
{2, 8, 9, 17},
{1, 4, 7, 7, 8},
{1, 2, 3, 4},
{15, 17, 19}};
int k = sizeof(arr)/sizeof(arr[0]);
int output[n*k];
mergeArrays(arr, 5, output);
cout << "Merged array is " << endl;
displayArray(output, n*k);
return 0;
}
【问题讨论】:
-
你尝试了什么,它是如何失败的?
-
我用这个测试用例尝试了相同的代码,但它不起作用。然后我将 n 的值更改为 5,并将 main 函数中的值从 3 更改为 5,但现在它在输出中显示了许多 0。检查我已编辑问题
-
请注意,您的数组大小不同,与要解决的问题相矛盾
标签: c++