How to remove duplicates from a list using an auxiliary array in Java?

前端 未结 8 775
南方客
南方客 2020-12-10 19:44

I am trying to remove duplicates from a list by creating a temporary array that stores the indices of where the duplicates are, and then copies off the original array into a

8条回答
  •  悲&欢浪女
    2020-12-10 20:34

    You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.

    double [] input = {1,2,3,3,4,4};
    Set tmp = new LinkedHashSet();
    for (Double each : input) {
        tmp.add(each);
    }
    double [] output = new double[tmp.size()];
    int i = 0;
    for (Double each : tmp) {
        output[i++] = each;
    }
    System.out.println(Arrays.toString(output));
    

提交回复
热议问题