[java]最长连续整数序列,调试 [英] [java]Longest consecutive integers sequence, debug
问题描述
我为这个问题写了一个方法:输入:整数数组返回:最长连续整数序列的长度.像:对于{9,1,2,3},返回3,cuz {1,2,3}
I have wrote a method for the question: input: an array of integers return: the length of longest consecutive integer sequence. like: for {9,1,2,3}, return 3, cuz{1,2,3}
该方法运行不正常.希望有人可以帮助我进行调试.
the method doesnt run well. hope someone could help me with debugging.
public int solution(int[] arr){
int counter = 1;
int max = arr[1];
//find the max in the array
for (int i : arr){
if (i > max){
max = i;
}
}
int[] nArr = new int[max];
for (int i : arr){
nArr[i] = i;
}
List<Integer> counters = new ArrayList<>();
for (int i = 0; i < max; i++){
if (nArr[i] == nArr[i+1] - 1){
counter++;
}else{
counters.add(counter);
counter = 1;
}
}
max = counters.get(1);
for (int i : counters){
if (i > max){
max = i;
}
}
return max; }
非常感谢!
推荐答案
您不需要使用ArrayList ...如果您想要的只是连续整数的最大数量,请尝试以下操作:
You dont need to use ArrayList... If all you want is max count of sequential integers, then try this:
int[] a = somethingBlaBla;
int counter = 0; // Stores temporary maxes
int secCounter = 0; //Stores final max
for(int j = 0; j<a.length-1; j++){ // Iterate through array
if(a[j] == a[j+1]-1){
counter++; // If match found then increment counter
if(counter > secCounter)
secCounter = counter; // If current match is greater than stored match, replace current match
}
else
counter = 0; // Reset match to accumulate new match
}
System.out.println(secCounter);
对于您的方法,我注意到的第一件事是 max
在数组中的值为 greatst (数字),而在数组中不是大小.因此,如果我的数组是 {1,2,3,45,6,7,8,9}
之类的东西,它将抛出 indexOutOfBoundsException
,因为它会尝试获取第45个元素不存在的数组中.
As for your method, the first thing I noticed is that max
has value of greatest number in array and not the size of array. So if my array is something like {1,2,3,45,6,7,8,9}
, it will throw indexOutOfBoundsException
because its gonna try get 45th element in array which is not present.
这篇关于[java]最长连续整数序列,调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!