public static Integer[] eliminateDuplicate(int[] a) {
if (a == null) {
throw new NullPointerException();
}
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
// include last element by default, if not the last element, do the check for duplication.
if (i == a.length - 1 || a[i] != a[i + 1]) {
list.add(a[i]);
}
}
return list.toArray(new Integer[0]);
}
|
|||||||||
|
Your function doesn't handle duplicates in the entire array, but only in consecutive entries. A better name might be The input is an You don't need to throw A micro-optimization would be to change to
Comparing against 0 is simpler than comparing against |
|||||
|
Minor point - don't use an old c-style for loop to iterate through an array unless you absolutely have to (and you don't have to here). Please, this is 2013 not 2003 - generics have been here for a decade. You can use foreach:
Using old-style c-loops always opens a possibility of a stupid error. Since you can cache the last value you inserted in the array, you don't have to use the old-style loop. My loop also has just one check, and that check is cheaper to do than yours (or 200_success's) because it doesn't need to do the array look-up. Note that my solution inserts the first value without checking, while yours does this for the final one. Not only is this more logical (I think), it eliminated a check from the logic. Your method is called eliminateDuplicates but it will only do that if the list has already been sorted. If that was not done, it will only eleminiate sequential duplicates. That is, it will turn (3, 1, 2, 3, 3, 4, 3) into (3,1,2,3,4,3). Is that what you want? The fact that you always keep the last member implies this, but how can we be sure? If it is so, either document the intent or maybe name the function more clearly (e.g. eliminateAdjacentDuplicates). If you want to eliminate all duplicates, then you could start by sorting the array. But since you are using the collections api, why not use a set?
Then you just need to turn the set back into an array. I may have gone on at unnecessary length, but that's because you didn't properly document your intent. Please, if you learn nothing else, learn this. |
|||||
|