【问题标题】:How to solve this geeksforgeeks question for the given testcase?如何为给定的测试用例解决这个 geeksforgeeks 问题?
【发布时间】: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;
}

https://www.geeksforgeeks.org/merge-k-sorted-arrays/amp/#aoh=15880638012294&referrer=https%3A%2F%2Fwww.google.com&amp_tf=From%20%251%24s

【问题讨论】:

  • 你尝试了什么,它是如何失败的?
  • 我用这个测试用例尝试了相同的代码,但它不起作用。然后我将 n 的值更改为 5,并将 main 函数中的值从 3 更改为 5,但现在它在输出中显示了许多 0。检查我已编辑问题
  • 请注意,您的数组大小不同,与要解决的问题相矛盾

标签: c++


【解决方案1】:

您的代码运行正常。当你用大括号括起来的列表初始化一个数组时,你没有设置的每个元素都被初始化为零,例如

int a[5] = {1, 2}

相当于

int a[5] = {1, 2, 0, 0, 0}

嵌套数组也是如此,例如

int arr[5][5] = {{2, 3, 5, 18},
                {2, 8, 9, 17},
                {1, 4, 7, 7, 8},
                {1, 2, 3, 4},
                {15, 17, 19}};

等价于

int arr[5][5] = {{2, 3, 5, 18, 0},
                {2, 8, 9, 17, 0},
                {1, 4, 7, 7, 8},
                {1, 2, 3, 4, 0},
                {15, 17, 19, 0, 0}};

您的数组包含 5 个零。

您可以使用

从输出中删除零
void displayArray(int arr[], int size)
{
for (int i=0; i < size; i++)
    if (arr[i]) cout << arr[i] << " ";
}

【讨论】:

  • 是的,我知道这是我的挑战,即我的老师要求我做的测试用例不应该是 0
  • @HrithikAgrawal 如果您知道,那么您的整个问题毫无意义。您对数组进行了排序,并且知道它包含 5 个零。但是您说输出中的 0 太多。我添加了一个没有零的版本。
猜你喜欢
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 2014-10-07
  • 1970-01-01
相关资源
最近更新 更多