我出现在网上测试中。这是我写的代码被拒绝了,你看到了什么问题?样本输入是{4,9,8}应该给出4对于4,8存在,对于9,4存在,对于8,4存在。但是{3,8,4}应该返回0,因为3需要6,7或1,并且这些值都不在数组中。类似地,{2,2,5,11,23},{7,7,3,6},{0}将返回1,因为它满足条件。我检查了这些示例输入,代码完美适用于这些,但我无法找到代码被拒绝的原因。我可能会缺少从不同的角度思考问题。请帮忙!
public static void main(String[] args) {
int [] arr = {4,9,8};
System.out.println(isBean(arr));
}
public static int isBean(int []a)
{
int next1=0;
int next2=0;
int next3=0;
for(int i=0;i<a.length;i++)
{
int n =a[i];
next1 = 2*n;
next2 =2*n+1;
next3= n/2;
boolean isValid = false;
for(int j=0;j<a.length;j++)
{
if(a[j]==next1 || a[j]==next2 || a[j]==next3)
{
isValid = true;
break;
}
}
if(!isValid)
return 0;
}
return 1;
}
答案 0 :(得分:0)
实际上这类问题需要必要的东西
import java.util.*;
public class Snippet {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int numberOfArrayElement = inp.nextInt();
// System.out.println(numberOfArrayElement);
int[] arr = new int[numberOfArrayElement];
int val = 0;
for (int i = 0; i < numberOfArrayElement; i++) {
val = inp.nextInt();
arr[i] = val;
}
// for (int i = 0; i < numberOfArrayElement; i++) {
// System.out.println(arr[i]);
// }
System.out.println(isBean(arr));
}
public static int isBean(int[] a) {
int next1 = 0;
int next2 = 0;
int next3 = 0;
int counter = 0;
for (int i = 0; i < a.length; i++) {
int n = a[i];
next1 = 2 * n;
next2 = 2 * n + 1;
next3 = n / 2;
boolean isValid = false;
// System.out.println("================================");
// System.out.println(a[i]);
// System.out.println(next1);
// System.out.println(next2);
// System.out.println(next3);
for (int j = 0; j < a.length; j++) {
if (a[j] == next1 || a[j] == next2 || a[j] == next3) {
isValid = true;
break;
}
}
if (isValid) {
counter++;
}
}
// System.out.println("Counter: " + counter);
// System.out.println("length of array: " + a.length);
if (counter == a.length)
return 1;
else
return 0;
}
}
3
4 9 8
1
5
2 2 五 11 23
1
1
2
0