【发布时间】:2015-06-16 22:39:01
【问题描述】:
问题
给定一个整数数组,如果数组中出现的每个 2 都与另一个 2 相邻,则返回 true。
twoTwo({4, 2, 2, 3})→truetwoTwo({2, 2, 4})→truetwoTwo({2, 2, 4, 2})→false
我的代码只是缺少这种情况
twoTwo({2, 2, 7, 2, 1}) → 假;但返回 true;
我的代码
public boolean twoTwo(int[] nums) {
int notFound = 0;
int i = 0;
boolean found = false;
if (nums.length == 0) {
return true;
}
if (nums.length == 1 && (nums[0] != 2)) {
return true;
}
for (i = 0; i < nums.length - 1; i++) {
if ((nums[i] == 2 && nums[i + 1] == 2)) {
found = true;
}
if (nums[nums.length - 1] == 2 && nums[nums.length - 2] != 2) {
return false;
}
if (nums[i] != 2) {
notFound++;
}
}
if (nums[i] != 2) {
notFound++;
}
if (notFound == nums.length) {
return true;
}
return found;
}
【问题讨论】:
-
我的代码只是缺少这种情况你为什么不通过添加来完成你的代码?
-
因为我尽最大努力创建干净的代码
-
问题陈述的重要部分是“给定一个整数数组,如果数组中出现的每个 2 都与另一个 2 相邻,则返回 true。”。其余的只是一些例子来阐明这意味着什么。您应该编写一个适用于所有种情况的程序,而不仅仅是示例。
-
@PatriciaShanahan 是的,我意识到了,谢谢。