Java 如何用多个数字连接数组
当我得到像[1,1,2,2,3,3,4]这样的数组时,我需要打印[1,2,3,4] 其他例子: 输入=[1,1,1,2]输出应=[1,2] 输入=[1,1,1,1]输出应为=[1]Java 如何用多个数字连接数组,java,arrays,integer,int,concatenation,Java,Arrays,Integer,Int,Concatenation,当我得到像[1,1,2,2,3,3,4]这样的数组时,我需要打印[1,2,3,4] 其他例子: 输入=[1,1,1,2]输出应=[1,2] 输入=[1,1,1,1]输出应为=[1] int count=1; //This for counts only the different numbers of the array input. for(int i=0; i<array.length-1;i++){ if(array[i+1]!=array[i]){
int count=1;
//This for counts only the different numbers of the array input.
for(int i=0; i<array.length-1;i++){
if(array[i+1]!=array[i]){
count++;
}
}
//New array only for the needed numbers.
Integer [] res = new Integer[count];
res[0] = array[0];
for(int i = 1;i<count;i++){
if(array[i]!=array[i+1]){
res[i]=array[i+1];
}
}
int count=1;
//这仅统计阵列输入的不同数目。
对于(int i=0;i一个问题是,即使在array[i]==array[i+1]
时,也会增加循环的计数器,这会导致输出数组具有null
值
另一个问题是在第二个循环中没有迭代输入数组的所有元素
如果使用两个索引,一个用于输入数组(循环变量),另一个用于输出数组中的当前位置,则两个问题都可以解决:
int count=1;
for(int i=0; i<array.length-1;i++){
if(array[i+1]!=array[i]){
count++;
}
}
Integer [] res = new Integer[count];
res[0] = array[0];
int resIndex = 1;
for(int i = 1; i < array.length - 1; i++){
if(array[i] != array[i+1]) {
res[resIndex] = array[i+1];
resIndex++;
}
}
int count=1;
对于(int i=0;i可能重复的错误在res[i]=array[i+1];
行中。您能找出这一行应该是什么,以及为什么吗?感谢dude做得很好。+++在某些情况下,条件resIndex
可能会更早地打破循环。
for(int i = 1 ; i < array.length - 1 && resIndex < count; i++)