給定一個(gè)整數(shù)數(shù)組,如果值 3 在數(shù)組中恰好出現(xiàn) 3 次,并且沒有 3 彼此相鄰,則返回 true。我只是一個(gè)初學(xué)者,在 codingbat 課程上遇到了一些麻煩。邏輯似乎沒問題。我跟“橡皮鴨”解釋了一千遍,沒發(fā)現(xiàn)問題。所有 codingbat 測試都按預(yù)期運(yùn)行,除了“其他測試”選項(xiàng)卡,我看不到數(shù)組中的具體數(shù)字,也無法與代碼進(jìn)行比較。我真的很困惑這個(gè)問題,希望你能幫助我!public boolean haveThree(int[] a) { int count = 0; //to count the appearences of 3 boolean doLado = false; //to check if a 3 is next to another 3 if(a[0] == 3) // check if first index is 3 count++; // add one if it is for(int i=1; i<a.length ; i++) { //loop starting at 1 to check rest of array if(a[i] == 3) { // check if i is 3 if(a[i-1] == a[i]) // if i its 3, check if the previous index was also 3 return false; // if it was indeed {..,3,3,..} return false else count++; // else add 1 to the counter } } if(count == 3) //if counter of 3s equals 3 return true return true; return false; //else return false}tests Expected Run haveThree([3, 1, 3, 1, 3])----------- → true true OK haveThree([3, 1, 3, 3])---------------→ false false OK haveThree([3, 4, 3, 3, 4])------------→ false false OK haveThree([1, 3, 1, 3, 1, 2])---------→ false false OK haveThree([1, 3, 1, 3, 1, 3])---------→ true true OK haveThree([1, 3, 3, 1, 3])------------→ false false OK haveThree([1, 3, 1, 3, 1, 3, 4, 3])---→ false false OK haveThree([3, 4, 3, 4, 3, 4, 4])----- → true true OK haveThree([3, 3, 3])------------------→ false false OK haveThree([1, 3])---------------------→ false false OK haveThree([3])------------------------→ false false OK haveThree([1])------------------------→ false false OK other tests-----------------------------X
2 回答

慕森王
TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊
你不處理null也不使用doLado;你也不需要if在最后測試count == 3. 我會把它簡化成類似的東西
public boolean haveThree(int[] a) {
if (a == null || a.length < 3) {
return false;
}
int count = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 3) {
if (i > 0 && a[i - 1] == 3) {
return false;
}
count++;
}
}
return count == 3;
}
添加回答
舉報(bào)
0/150
提交
取消