我必須編寫一個方法,該方法返回整數值ArrayList的第二大索引。如何在java中查找arraylist的第二大索引
陣列列表是: 4 8 15 16 23 42 97 56 95 85 63 41 52 99 97 Q
的Q是有標記的輸入的結束。我正在使用fileIn.hasNextInt()來讀取輸入並檢查它是否是整數。
我的邏輯問題是它只循環訪問ArrayList並返回ArrayList的最後一個索引而不是第二大值的索引。
這裏是我的代碼:
public static int secondMaxIndex(ArrayList<Integer> intArray){
int largest = intArray.get(0);
int largest2 = intArray.get(0);
int maxIndex2 = 0;
for(int i = 0; i <= intArray.size() - 1; i++){
if(largest < intArray.get(i)){
largest = intArray.get(i);
}
}
for(int j = 0; j <= intArray.size() - 1; j++){
if(intArray.get(j) < largest){
maxIndex2 = j;
}
}
return maxIndex2;
}
不錯的使用迷失號碼。 =) –
你的第二個for循環遍歷整個數組並返回小於第一個循環中已找到的最大值的最後一個值 –