0
我的程序正在嘗試查找數組中最長的連續序列,但輸出錯誤。刪除數組中無用的元素
public class longsec {
public int[] longestForward(int[] arr){
int subSeqLength = 1;
int longest = 1;
int indexStart = 0;
int indexEnd = 0;
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] == arr[i + 1] - 1)
{
subSeqLength++;
if (subSeqLength > longest)
{
longest = subSeqLength;
indexStart = i + 2 - subSeqLength;
indexEnd = i + 2;
}
}
else
subSeqLength = 1;
}
int T[] = new int[arr.length];
for (int i = indexStart; i < indexEnd; i++)
T[i]= arr[i];
return T;
}}
輸入
{23,10,22,5,33,8,9,21,50,41,60,80,99,22,23,24,25,26,27 }
輸出
[0,0,0,0,0,0,0,0,0,0,0,0,0,22,23,24,25,26,27]
right output
[22,23,24,25,26,27]
我做錯了什麼?謝謝。
'int T [] = new int [arr.length];'應該是'int T [] = new int [indexEnd-indexStart + 1];'也許不是'+ 1'。我需要睡眠。無論如何,'for'循環將需要調整。 'T [i] = arr [i + indexStart];'或類似的東西。 – bradimus
它給了我「java.lang.ArrayIndexOutOfBoundsException」如果我這樣做。 –
您是否調整過'for'循環? 'for(int i = 0; i
bradimus