问题描述
我试图想出一个解决
编程挑战提示符,比排序数组的一个副本,并在返回的最后9 elements.So的总和我试着写在
线性解决方案的显着另一个解决方案 的#include<的iostream>
INT SumNLargest(INT * ANDATA,诠释大小,INT N)
{
//总和N的整数数组,其中每个整数是0到9之间最大的整数
INT cntArr [] = {0,0,0,0,0,0,0,0,0,0};
的for(int i = 0; I<大小; ++ I)++ cntArr [ANDATA [I]];
INT总和= 0;
的for(int i =大小 - 1; I> = 0; --i)
{
总和+ =(N - cntArr [I])> = 0? cntArr [我] * I:N * I;
--N;
如果(N< = 0)打破;
}
返回总和;
}
诠释的main()
{
INT myArray的[] = {1,2,3,4,5,6,7,8,9,10,11,11,11,12,15};
性病::法院<< SumNLargest(myarray的,的sizeof(myarray的)/的sizeof(INT),2);
返回0;
}
但我得到的错误
请参阅: HTTP://$c$cpad.org/UILgXDzQ
这是我的逻辑有问题?如果是这样,在哪里?此外,有没有,我应该已经做了,而不是一个更优雅的线性解决方案?
(最后,我意识到,我的解决方案假定 N'GT; =大小> = 1
,但我认为典型的编程采访让我做这样的假设使我没有浪费时间写处理意外输入一串错误)
在
您code调用未定义行为 的for(int i = 0; I<大小; ++ I)
++ cntArr [ANDATA [I]];
当你进入第十一元素( I = 10
),因为 cntArr
只有10个元素。
内存检查,如AddressSanitizer将立即指示你。
你不是真的调用系统调用来创建一个新的socket,但是,作为一个未定义的行为的结果,什么事情都可能发生。
I'm trying to come up with a solution to the
programming challenge prompt, a solution other than the obvious one of sorting a copy of the array and returning the sum of the last 9 elements.So I tried writing the linear solution below
#include <iostream>
int SumNLargest(int* anData, int size, int n)
{
// Sum n largest integers in an array of integers where every integer is between 0 and 9
int cntArr [] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < size; ++i) ++cntArr[anData[i]];
int sum = 0;
for (int i = size - 1; i >= 0; --i)
{
sum += (n - cntArr[i]) >= 0 ? cntArr[i] * i : n * i;
--n;
if (n <= 0) break;
}
return sum;
}
int main()
{
int myArray [] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 11, 12, 15};
std::cout << SumNLargest(myArray, sizeof(myArray)/sizeof(int), 2);
return 0;
}
but I'm getting the error
See: http://codepad.org/UILgXDzQ
Is this a problem with my logic? If so, where? Also, is there a more elegant linear solution that I should've done instead?
(And finally, I realize that my solution assumes n >= size >= 1
, but I think the typical programming interview allows me to make that assumption so that I don't have to waste time writing a bunch of error handling for unexpected input)
Your code invokes undefined behavior at
for (int i = 0; i < size; ++i)
++cntArr[anData[i]];
when you access the eleventh element (i = 10
) because cntArr
has only 10 elements.
A memory checker such as AddressSanitizer would indicate you that immediately.
You're not really calling a system call to create a new socket but, as result of an undefined behavior, anything could happen.
这篇关于&QUOT;不允许的系统调用:SYS_socketcall&QUOT;当我尝试解决&QUOT;总和的阵列和QUOT中最大的n个整数;编程挑战的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!