-1

I have been given this question to do for a lab, which is to take in an array of ints from a user, then remove any duplicates and finally return the array in the same order. WE are restricted from using Hashsets and other set related ideas. There is no reason to order the list as it has to be in it's original order. Can anyone give me some tips or pointers in the right direction, I have been using some other quesitons already answered for some help. Here is what I have so far:

public class Q3C {
    public static void main() {
        System.out.println("Enter your numbers please: ");
        Scanner numbers = new Scanner(System.in);
        String nums = numbers.nextLine();

        String[] parts = nums.split(" ");//
        int[] n1 = new int[parts.length];//
        for (int n = 0; n < parts.length; n++) {
            n1[n] = Integer.parseInt(parts[n]);
        }

    }

I was thinking of creating another method, called removeDuplicates and sending the array to it which will then go through it, check each index for other duplicates and set all duplicates to the next index value. I just can not get that down though. Any help is much appreciated.

Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
  • Any runtime constraints? – tilois Feb 08 '14 at 22:21
  • @tilois not really, though as fast and efficient as possible is preferable. My lecturer is hell bent on efficiency and big O notation. – Demostroyer Feb 08 '14 at 22:24
  • There was discussion recently of a very similar problem. Since this is homework, I'm gonna make you find it yourself... – keshlam Feb 08 '14 at 22:32
  • possible duplicate of [algorithm removing duplicate elements in array without auxillay storage](http://stackoverflow.com/questions/21613204/algorithm-removing-duplicate-elements-in-array-without-auxillay-storage) among others. – Brian Roach Feb 08 '14 at 23:02

1 Answers1

0

Here a result using only arrays (no collections):

int[] input = {1, 3, 4, 1, 2, 2, 4, 5, 6, 6};

int[] result = new int[input.length];
int resultSize = 0;

for (int anInput : input) {
    boolean found = false;
    for (int j = 0; j < resultSize; j++) {
        if (anInput == result[j]) { // already exists
            found = true;
            break;
        }
    }
    if (!found) { // add
        result[resultSize++] = anInput;
    }
}

// copy to new result only real values
int[] newResult = new int[resultSize];
System.arraycopy(result, 0, newResult, 0 , resultSize);

System.out.println("result = " + Arrays.toString(newResult));

Result is:

result = [1, 3, 4, 2, 5, 6]
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28