鑑於整數數組,返回真,如果每出現的陣列中的2是下一個到另一個2.
twoTwo({4, 2, 2, 3})
→true
twoTwo({2, 2, 4})
→true
twoTwo({2, 2, 4, 2})
→false
我的代碼只mising這種情況下
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;
}
_my代碼只是在這種情況下_你爲什麼不通過添加它來完成你的代碼? –
因爲我盡了最大的努力創建了一個乾淨的代碼 – Bodhert
問題陳述的重要部分是「給定一個int數組,如果數組中出現的每個2都與另一個2相鄰,則返回true」。其餘的只是一些例子來澄清這是什麼意思。你應該編寫一個適用於所有**案例的程序,而不僅僅是例子。 –