[英][java]Longest consecutive integers sequence, debug
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}
例如:对于{9,1,2,3},返回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; }
thanks a lot!!! 非常感谢!!!
You dont need to use ArrayList... If all you want is max count of sequential integers, then try this: 您不需要使用ArrayList ...如果您想要的只是连续整数的最大数量,请尝试以下操作:
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);
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. 至于您的方法,我注意到的第一件事是
max
在数组中具有最大数的值,而不是数组的大小 。 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. 因此,如果我的数组类似
{1,2,3,45,6,7,8,9}
,它将抛出indexOutOfBoundsException
因为它会尝试获取数组中不存在的第45个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.