Home:ALL Converter>Remove duplicates from array by shifting elements to the end

Remove duplicates from array by shifting elements to the end

Ask Time:2018-07-23T14:18:15         Author:AmacOS

Json Formatter

I need to write method which takes String[] array as input and returns the given array without duplicates. Using additional array inside method is not allowed, all logic must be done in the input array. All duplicates must be shifted to the end of array and truncated. The template for the method:

public String[] remove(String[] array) {
    //Logic is here
    return Arrays.copyOf(array, array.length - numberOfDuplicates)
}

Here is what I have done so far. This works for some input, but sometimes it gives incorrect result:

public String[] remove(String[] array) {
    int numberOfDuplicates = 0;

    for (int i = 0; i < array.length - 1 - numberOfDuplicates; i++) {
        for (int j = 0; j < array.length - 1 - numberOfDuplicates; j++) {
            if (i != j && array[i].equals(array[j])) {
                String temp = array[array.length - 1 - numberOfDuplicates];
                array[array.length - 1 - numberOfDuplicates] = array[j];
                array[j] = temp;
                numberOfDuplicates++;
            }
        }
    }
    return Arrays.copyOf(array, array.length - numberOfDuplicates);
}

Could you help me with this, please? Thanks a lot!

Author:AmacOS,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51472593/remove-duplicates-from-array-by-shifting-elements-to-the-end
GolamMazid Sajib :

When u get match just swap with latest last position. Try with this:\n\npublic static String[] remove(String[] array) {\n int len = array.length;\n for (int i = 0; i < len; i++) {\n for (int j = i+1; j < len && j > 0; j++) {\n if(array[i].equals(array[j])){\n String tmp = array[len -1];\n array[len - 1] = array[j];\n array[j] = tmp;\n len--;\n j--;\n }\n }\n }\n return Arrays.copyOf(array, len);\n}\n",
2018-07-23T10:41:13
yy