【发布时间】:2017-05-29 18:21:30
【问题描述】:
我正在编写一个程序,它扫描一个数组并生成包含总和可被 3 整除的元素的最长子数组的长度。我在这里使用另一个问题的概念,使用前缀和概念 - 扫描通过 modolu 3 得出的第一个和最后一个总和给出 0,1,2,计算每组之间的差异并返回三组中最大的一个。
我决定使用随机数组生成器对其进行测试。 90% 的时间它有效,但在其他情况下,它会错过几个数字的正确答案。 知道有什么问题吗?
我已经包含了一个测试器,其中包含一个执行相同操作的非高效方法。图片包括:
输出:
84|4|94|27|85|10|87|11|66|34|66|42|26|65|12|93|14|
数组大小为:17
坏事:15
我的:13
代码:
import static java.lang.Math.*;
import java.util.Random;
public class Q1 {
public static void main(String args[]) {
Random rand = new Random();
int[] a = new int[rand.nextInt(100)];
for (int i = 0; i < a.length; i++)
{
a[i] = rand.nextInt(100);
System.out.print(a[i] + "|");
}
System.out.println();
System.out.println("array size is: " + a.length);
System.out.println("Bad What: " + badWhat(a));
System.out.println("My What: " + what(a));
}
public static int what(int[] a) {
int sumLeft = 0, sumRight = 0;
int zero, one, two;
int firstZero = 0, firstOne = 0, firstTwo = 0, lastZero = 0, lastOne = 0, lastTwo = 0;
for (int i = 0; i < a.length; i++) {
sumLeft += negMod(a[i])%3;
sumRight += negMod(a[a.length - 1 - i]%3);
if ((sumLeft) % 3 == 0)
firstZero = i;
if ((sumRight) % 3 == 0)
lastZero = i;
if ((sumLeft) % 3 == 1)
firstOne = i;
if ((sumRight) % 3 == 1)
lastOne = i;
if ((sumLeft) % 3 == 2)
firstTwo = i;
if ((sumRight) % 3 == 2)
lastTwo = i;
}
firstOne++;
firstTwo++;
zero = lastZero - firstZero + 1;
one = lastOne - firstOne;
two = lastTwo - firstTwo;
int result = max(max(zero, one), two);
if (firstZero +1 > result)
result = ++firstZero;
return result;
}
public static int negMod (int a)
{
if (a<0)
{
return (a+3);
}
return a;
}
public 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 badWhat (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 % 3 == 0) {
if (j - i + 1 > temp)
temp = j - i + 1;
}
}
}
return temp;
}
}
【问题讨论】:
-
“90% 的时间它可以工作,但在其他情况下它会错过几个数字的正确答案” - 发布示例输入/输出/预期输出元组。
-
感谢您的反馈,我已经编辑了帖子。
-
您是否有任何理由将它们作为屏幕截图而不是实际代码包含在内?有人应该如何将屏幕截图插入他们的代码并找出您的代码行为不端的原因?
-
我已经将输出包含在文本中了,不用生气,这是我第一次在这里提问。
-
@Jamaico:除非有人在这里使用攻击性词语,否则不要过多解读人们的语气。如果它大大超过了一条线,您可以将其标记为版主,但除此之外,请记住高级代表用户不断看到相同的发布问题,他们(我们)希望通过帮助人们来提高 Stack Overflow 的效率在第一次编辑中获得合理正确/可回答的问题。
标签: java arrays modulus sub-array