问题是将整数数组中的簇定义为全部相同值的元素的最大序列。例如,数组 {3, 3, 3, 4, 4, 3, 2, 2, 2, 2, 4}
有 5 个簇, {3, 3, 3 }
、{4, 4}
、{3}
、{2, 2, 2, 2}
和 {4}
。数组的簇压缩将每个簇替换为簇中重复的数字。因此,前一个数组的簇压缩将为 {3, 4, 3, 2, 4}
。第一个簇 {3, 3, 3}
被单个 3 替换,依此类推。
public static void main(String[] args) {
int[] givenArray = {1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1};
System.out.println("Clustered Array = " + Arrays.toString(isTrivalent(givenArray)));
}
public static int[] isTrivalent (int[] a){
List<Integer> cluster = new ArrayList<Integer>();
for (int i=0; i<a.length ; i++ ) {
if(i == 0){
cluster.add(a[i]);
}else{
if(cluster.get(i-1) != a[i]) cluster.add(a[i]);
}
}
int[] arr = new int[cluster.size()];
for (int j =0; j<cluster.size() ; j++) {
arr[j] = cluster.get(j);
}
return arr;
}
但是我收到了ArrayOutOfBoundException
。我做错了什么?
最佳答案
改变
if(cluster.get(i-1) != a[i]) cluster.add(a[i]);
至
if(a[i-1] != a[i]) cluster.add(a[i]);
cluster.get(i-1)
可能不存在。
关于Java ArrayList 中的 ArrayOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30502562/