【发布时间】:2015-08-22 18:04:20
【问题描述】:
我有这段代码,据我了解,它在给定数组中搜索最大数量的连续数字,总和是偶数。
private static int f (int[]a, int low, int high)
{
int res = 0;
for (int i=low; i<=high; i++)
res += a[i];
return res;
}
public static int what (int []a)
{
int temp = 0;
for (int i=0; i<a.length; i++)
{
for (int j=i; j<a.length; j++)
{
int c = f(a, i, j);
if (c%2 == 0)
{
if (j-i+1 > temp)
temp = j-i+1;
}
}
}
return temp;
}
例如,数组 [-3,4,8,-1,15] 应该返回“4”作为答案,因为 -3+4+8-1 = 8,而 8 是偶数。
我需要一个关于如何提高效率的想法(+现在的效率是多少?O(n^3)?)
提前致谢。
【问题讨论】:
-
提示:你只需要计算数组中有多少奇数,数组中有多少偶数。
-
需要计算奇数和偶数的个数说 numOdd 和 numEven - 如果那个 numOdd 是偶数,那么你的答案是 (numOdd + numEven) 否则你的答案是 (numOdd + numEven - 1)
标签: java arrays performance sum