-3

I want to delete duplicates in a double[] array. Unfortunately, I cannot use an ArrayList or whatsoever, it has to be a "normal" double array. I tried to use the binarySearch() method of the class Array, but could not find a good solution to it, because I must not only search for but also delete the duplicates. Then I would have to reduce the length every time I delete such a duplicate.

Is there any solution for this problem?

DynamiX
  • 49
  • 4
  • You can just null-out elements on the first go and then, at the end, do another cleanup loop where you copy over into a new array and skip all nulls. BinarySearch can only be applied to sorted arrays - I guess you have to maintain your array order, so binary search wont help you (unless you are willing to copy over into a sorted auxiliary array first). If you can not use an utility `Set`, you wont find a fast solution anyways - in which case you can just go with the naiive straightforward solution of solving "array contains" with a simple loop each time. – Zabuzard Mar 02 '22 at 16:05

2 Answers2

1
public static double[] removeDuplicates(double[] arr) {
    return Arrays.stream(arr).distinct().toArray();
}
oleg.cherednik
  • 15,340
  • 4
  • 20
  • 31
0
double[] arr = {...};

double[] removed = new double[arr.length];

for (int k=0; k<removed.length; k++) {
  boolean b = false;

  for (int i=0; i<arr.length; i++) {
    b = false;

    for (int j=0; j<removed.length; j++) {

      if (arr[i] == arr[j] && i != j) b = true;
    }

    if (!b) removed[k] = arr[i];

  }

}

// Then parse through 'removed' to make a smaller list of all initialized elements.