【发布时间】:2016-10-27 10:54:59
【问题描述】:
给定一个 (6*6) 二维数组,我们必须在其中找到一个沙漏的最大和。 例如,如果我们在一个全零的数组中使用数字 1 创建一个沙漏,它可能看起来像这样:
沙漏的总和是其中所有数字的总和。上面沙漏的总和分别是 7、4 和 2。
我为它编写了如下代码。这基本上是一个有竞争力的编程问题,由于我是该领域的新手,我编写的代码的复杂性非常糟糕。也许程序无法生成在规定的时间内所需的输出。下面是我的代码:
int main(){
vector< vector<int> > arr(6,vector<int>(6));
for(int arr_i = 0;arr_i < 6;arr_i++)
{
for(int arr_j = 0;arr_j < 6;arr_j++)
{
cin >> arr[arr_i][arr_j];
}
} //numbers input
int temp; //temporary sum storing variable
int sum=INT_MIN; //largest sum storing variable
for(int i=0;i+2<6;i++) //check if at least3 exist at bottom
{
int c=0; //starting point of traversing column wise for row
while(c+2<6) //three columns exist ahead from index
{
int f=0; //test case variable
while(f!=1)
{ //if array does not meet requirements,no need of more execution
for(int j=c;j<=j+2;j++)
{ //1st and 3rd row middle element is 0 and 2nd row is non 0.
//condition for hourglass stucture
if((j-c)%2==0 && arr[i+1][j]==0||((j-c)%2==1 && arr[i+1][j]!=0)
//storing 3 dimensional subarray sum column wise
temp+=arr[i][j]+arr[i+1][j]+arr[i+2][j]; //sum storage
else
f=1; //end traversing further on failure
if(sum<temp)
sum=temp;
f=1;//exit condition
}//whiel loop of test variable
temp=0; //reset for next subarray execution
c++; /*begin traversal from one index greater column wise till
condition*/
}// while loop of c
}
}
cout<<sum;
return 0;
}
这是我在时间间隔内无法处理的代码的实现。考虑到时间复杂度,请提出一个更好的解决方案,并随时指出我在理解问题方面的任何错误。问题来自 Hackerrank。 如果您仍然需要,这里是链接: https://www.hackerrank.com/challenges/2d-array
【问题讨论】:
-
令人惊讶的是,图片链接不起作用。请参阅底部的链接以了解完整的问题。
-
如果您的代码已经在工作,您可能会更幸运地在 codereview.stackexchange.com 上发布此内容。
-
你测试过它的一些输入吗?
-
在 6x6 数组上循环不会花费很长时间 - 我怀疑您的代码中某处存在无限循环。
whiles 特别可疑 - 对于一个简单的算法,您最多需要两个fors。 -
//1st and 3rd row middle element is 0 and 2nd row is non 0.是什么意思?
标签: c++ arrays multidimensional-array