【发布时间】:2023-03-09 07:20:01
【问题描述】:
public static void main(String[] args) {
int[] a = { 0, 0, 1, 1, 1, 1, 1, 0, 0 };
int[] b = { 0, 0, 1, 0, 1, 1, 1, 0, 0 };
System.out.println(consecutiveEqualofSize(a, 5));
System.out.println(consecutiveEqualofSize(b, 5));
System.out.println(consecutiveEqualofSize(b, 3));
}
public static boolean consecutiveEqualofSize(int[] a, int size) {
int count = 0;
boolean flag = false;
for (int i = 0; i < a.length; i++) {
if (flag) {
break;
}
if (a[i] == 1) {
for (int j = i; j < i + size; j++) {
if (j == a.length - 1)
break;
if (a[j] == 1) {
count++;
} else {
count = 0;
break;
}
if (count == size)
flag = true;
}
}
}
return flag;
}
main方法中的代码打印“True, False, True”。我是编程的新学生,想要一些提示
【问题讨论】:
-
您似乎只对连续的 1 感兴趣 - 是吗?此外,是否必须恰好有
x连续元素(以 0 或数组结尾结尾)连续序列可以长于 x 吗?在您的示例中,它们是准确的。 -
正确只对连续的 1 感兴趣。最初,我在该方法背后的想法是在数组的任何位置确认大小为 x 的相等连续元素。 (如果它从中间开始,或者接近尾声)。连续元素可以比x长,我只是整合了int大小来演示一个布尔方法。
标签: java arrays methods integer