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

前端 未结 8 760
南方客
南方客 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<Double> tmp = new LinkedHashSet<Double>();
    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));
    
    0 讨论(0)
  • 2020-12-10 20:36
    import java.util.HashSet;
    
    import sun.security.util.Length;
    
    
    public class arrayduplication {
    public static void main(String[] args) {
            int arr[]={1,5,1,2,5,2,10};
            TreeSet< Integer>set=new TreeSet<Integer>();
            for(int i=0;i<arr.length;i++){
                set.add(Integer.valueOf(arr[i]));
            }
            System.out.println(set);
    
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题