【问题标题】:How to concatenate array with multiple numbers如何将数组与多个数字连接
【发布时间】:2023-03-10 21:57:02
【问题描述】:

当我得到像 [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]){
                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];
            }
        }

输入 [1,1,2,2,3,3,4] 我得到 [1, 2, null, 3]。

应该是 [1,2,3,4]。

【问题讨论】:

  • Array of unique elements?的可能重复
  • 您的错误在res[i]=array[i+1]; 行中。你能弄清楚这条线应该是什么,为什么?

标签: java arrays integer int concatenation


【解决方案1】:

一个问题是,即使在 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++;
    }
}

编辑:

按照 fabian 的建议,将第二个循环更改为

for(int i = 1 ; i < array.length - 1 && resIndex < count; i++)

如果输入数组的最后一个唯一编号重复多次,可以稍微加快速度。

【讨论】:

  • 谢谢老兄干得好。 +++
  • 条件resIndex &lt; count 在某些情况下可能会提前中断循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 2011-11-09
  • 2017-07-17
  • 1970-01-01
相关资源
最近更新 更多