我想编写一个方法来检查数组是否为123,is123是一个具有整数1,2,3的多次重复序列的数组。int [] arr1 = {1,2,3,1,2, 3} 应该返回 1,因为 arr1 是123,否则返回 0。
示例 - int[] arr = {1, 1, 2, 3} 应返回 0。 int[] arr = {1, 2, 3, 0, 1, 2, 3} 应返回 0。 int [] arr = {1, 2, 3} 应该返回 1。请帮我仅使用暴力方法解决这个问题,提前感谢您的帮助。这是我糟糕的尝试。
public static int is123Array(int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] == 1 && a[i + 1] == 2 && a[i + 2] == 3) {
return 1;
}
}
return 0;
}
最佳答案
您的实现已接近尾声!
在检查索引 i
时,您需要将 i
增加 3
而不是 1
、i + 1
和 i + 2
在每次迭代期间。
您也在 if 语句中提前返回; [1, 2, 3, 4]
数组将返回 1
,因为它在找到 [1, 2, 3]< 的第一个三元组后返回
。要解决此问题,如果没有找到 [1, 2, 3]
的三元组,则应返回 0
,这样您就可以确保数组不是一个解决方案。
您修复的代码可能如下所示:
public static int is123Array(int[] a) {
// If the length of the array is 0 or not a multiple of 3, then
// you know it isn't a solution.
if (a.length == 0 || a.length % 3 != 0) {
return 0;
}
for (int i = 0; i < a.length; i += 3) {
if (a[i] != 1 || a[i + 1] != 2 || a[i + 2] != 3) {
return 0;
}
}
return 1;
}
我还建议返回 boolean
而不是 int
,因为唯一可能的返回值是 0
和 1
,分别表示 false
和 true
。
关于java - 检查数组是否为123,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57422306/