有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何更改数组,使重复元素只显示一次?

这与仅删除重复项略有不同(可以使用LinkedHashSet)。如果我在Java中有这样一个数组,我从byte[]数组获得,然后转换为String数组:

[0,0,0,0,1,1,1,1,0,0,0,0,2,2,2,2,3,3,3,3,0,0,0,0]

有没有办法把它改成这样:

[0, 1, 0, 2, 3, 0]

我试过使用HashSetLinkedHashSet,但它没有达到我想要的效果。即使在技术上是重复的,0的不同集合也会保持不变。非常感谢


共 (2) 个答案

  1. # 1 楼答案

    扫描输入数组,只发出每个序列的第一个值。这个伪C#算法应该指导您:

    int[] a = ... // input array
    int[] b = new int[a.Length]; // same size
    int i, j;
    
    if (a.Length == 0)
    {
        // return a zero-length array
    }
    
    i = 0;
    j = 0;
    while (i < a.Length)
    {
        b[j] = a[i];
        while(i < a.Length && a[i] == b[j])
        {
            i++;
        }
        j++;
    }
    
    // return the sub-array of "b" from "0" to "j - 1"
    

    就这些

  2. # 2 楼答案

    您可能希望在元素上循环,并将不连续的重复元素复制到新集合:

    public class Tester {
    
        public static void main(String[] args){
             int[] values = {0,0,0,0,1,1,1,1,0,0,0,0,2,2,2,2,3,3,3,3,0,0,0,0};
    
             List<Integer> output = new ArrayList<Integer>();
             if(values.length > 0){
                int previous = values[0];
                output.add(previous);
                for(int value : values){
                    if(previous != value){
                        output.add(value);
                    }
                    previous = value;
                }
             }
             System.out.println(output); // [0, 1, 0, 2, 3, 0]
        }
    }