来自一些在线测试的问题:
由于该问题已受版权保护,因此无法复制。可以在这里找到问题:http : //codility.com/c/run/demo534WQK-UBH
从示例中可以看到:
P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7
元素的总和始终是常数(3 + 10)=(4 + 9)=(6 + 7)等。我们还注意到左侧的数字增加而右侧的数字减少。
我的解决方案:
class Solution
{
public int solution(int A[])
{
long sum = 0;
for (int i = 0; i < A.length; i++)
{
sum += A[i];
}
long currSum = 0;
long ans = Long.MAX_VALUE;
for (int i = 0; i < A.length; i++)
{
currSum += A[i];
long diff = Math.abs((sum - currSum) - currSum);
ans = Math.min(ans, diff);
}
return (int) ans;
}
}
http://codility.com/demo/results/demo8MC2GU-7BK/
现在有什么办法,我可以找出为什么我的解决方案在2个测试用例中失败的原因?我知道可能看不到输入内容,因此要依靠代码检查。
的问题是,在你的答案的“P”的变量是0 <P <= N。
但是要求是0 <P <N。
所以你需要改变第二个循环
for (int i =0;i<A.length;i++)
到
for (int i =0;i<A.length-1;i++)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句