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

前端 未结 8 767
南方客
南方客 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:30

    Done for int arrays, but easily coud be converted to double.

    1) If you do not care about initial array elements order:

    private static int[] withoutDuplicates(int[] a) {
        Arrays.sort(a);
        int hi = a.length - 1;
        int[] result = new int[a.length];
        int j = 0;
        for (int i = 0; i < hi; i++) {
            if (a[i] == a[i+1]) {
                continue;
            }
            result[j] = a[i];
            j++;            
        }
        result[j++] = a[hi];
        return Arrays.copyOf(result, j);
    }
    

    2) if you care about initial array elements order:

    private static int[] withoutDuplicates2(int[] a) {
        HashSet keys = new HashSet();
        int[] result = new int[a.length];
        int j = 0;
        for (int i = 0 ; i < a.length; i++) {
            if (keys.add(a[i])) {
                result[j] = a[i];
                j++;
            }
        }
        return Arrays.copyOf(result, j);
    }
    

    3) If you do not care about initial array elements order:

    private static Object[] withoutDuplicates3(int[] a) {
        HashSet keys = new HashSet();
        for (int value : a) {
            keys.add(value);
        }
        return keys.toArray();
    }
    

提交回复
热议问题