5 回答

TA贡献1836条经验 获得超3个赞
您可以只使用来获取是否在列表中的arr.contains()
布尔值。Integer
然后您可以将此值转换为YES
or NO
(如果您确实需要它):
String yesNo = arr.contains(k) ? "YES" : "NO";

TA贡献1784条经验 获得超8个赞
这将起作用:
static String findNumber(List<Integer> arr, int k) {
String res = "YES";
for (int i = 0; i < arr.size(); i++) {
if (k == arr.get(i))
res = "YES";
break;
else
res = "NO";
}
return res;
}
一旦找到整数,就必须停止循环,您可以使用break

TA贡献1853条经验 获得超9个赞
使用流:
static String findNumber(List<Integer> arr, int k) {
return arr.stream()
.filter(e -> e == k)
.findFirst()
.map(e -> "YES")
.orElse("NO");
}

TA贡献1859条经验 获得超6个赞
尝试优化您的代码....
方式 1(使用 for-each 循环):
static String findNumber(List<Integer> arr, int k) {
for (Integer integer : arr) {
if (integer == k) {
return "YES";
}
}
return "NO";
}
另一种方法是(使用三元运算符):
static String findNumber(List<Integer> arr, int k) {
return arr.contains(k) ? "YES" : "NO";
}

TA贡献1835条经验 获得超7个赞
你的代码的主要问题是,即使它在 ArrayList 中找到了一个整数对象,在设置 res = Yes 之后,它仍然继续迭代。因此,有可能列表中有其他值不是所需的数据类型,从而将 res 设置回否。这里的解决方案是使用跳转语句,例如 break,它会在出现时立即终止循环过程。遇到整数。希望能帮助到你!
添加回答
举报