我必须编写一个方法,如果整数数组中存在三个 3(假设它们不连续),则该方法返回 true。 我在这里编写了这段代码:但是,它返回 true (它不应该这样做)。有人可以指出我的错误吗? arr[]={{4,3,5,2,3,3};
此外,这是一个线性算法。可以做得更好吗?
public static boolean consecutiveThree(int[] arr) {
int x=0;
for(int i=0;i<arr.length-1;i++) {
if((arr[i]!=3 && arr[i+1]==3) || (arr[i]==3 && arr[i+1]!=3)) {
x++;
//continue;
}
if(x==3)
return true;
}
return false;
}
最佳答案
你说:
returns true if three 3s are present in an integer array(provided they are not consecutive)
我将其解释为至少有三个 3,并且没有两个 3 是相邻的。
public static boolean hasThreeNonconsecutiveThrees(int... values) {
int count = 0, streak = 0;
for (int value : values) {
if (value != 3)
streak = 0;
else if (++streak == 2)
return false; // Found two consecutive (adjacent) 3s
else
count++;
}
return (count >= 3);
}
测试
System.out.println(hasThreeNonconsecutiveThrees(4,3,5,2,3,3)); // false
System.out.println(hasThreeNonconsecutiveThrees(4,3,5,3,2,3)); // true
System.out.println(hasThreeNonconsecutiveThrees(1,2,3,4,3)); // false
System.out.println(hasThreeNonconsecutiveThrees(4,3,5,3,3,3)); // false
输出
false
true
false
false
关于java - 搜索算法(优于线性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407800/