Imagine this was your input:
Then, according to your algorithm, tempa should be:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8, ....Exception!!! Value: 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 5, 6, 7, 8, 6, 7, 8, 7, 8, 8
Why do you have this problem? Since the first set of nested loops doesn't stop you from trying to insert duplicate indices of repeating arrays!
What is the best solution?
Use the kit! Sets ensure that there are no duplicate entries. If you create a new Set and then add all the elements of the array to it, Set will change the duplicates. Then it's just a matter of returning from the set to the array.
Alternatively, here is a very C-shaped way to do the same:
//duplicates will be a truth table indicating which indices are duplicates. //initially all values are set to false boolean duplicates[] = new boolean[items.length]; for ( int i = 0; i< numItems ; i++) { if (!duplicates[i]) { //if i is not a known duplicate for(int j = i + 1; j < numItems; j++) { if(items[i] ==items[j]) { duplicates[j] = true; //mark j as a known duplicate } } } }
I will leave it to you to figure out how to finish.