此方法必须从位于2个索引点的传递数组中删除重复元素。然而,我了解到我们不允许使用Arraylist或LinkedLists,只能使用Arrays。我怎样才能做到这一点?
public Animal[] removeDuplicateAnimals(Animal[] animals, int fromIndex, int toIndex) {
int constFromIndex = fromIndex;
ArrayList<Animal> uniqueAnimals = new ArrayList<Animal>();
Animal[] uniqueAnimalsArray = new Animal[0];
uniqueAnimals.addAll(Arrays.asList(Arrays.copyOfRange(animals, 0, fromIndex)));
boolean existingFlag;
while (fromIndex < toIndex) {
existingFlag = false;
if(uniqueAnimals.size() == 0)
uniqueAnimals.add(animals[fromIndex]);
else {
int j = (constFromIndex - 1) > 0 ? (constFromIndex - 1): 0;
for (; j < uniqueAnimals.size(); j++)
if(uniqueAnimals.get(j).equals(animals[fromIndex])) {
existingFlag = true;
break;
}
if(!existingFlag)
uniqueAnimals.add(animals[fromIndex]);
}
fromIndex++;
}
uniqueAnimals.addAll(Arrays.asList(Arrays.copyOfRange(animals, toIndex, animals.length)));
return uniqueAnimals.toArray(uniqueAnimalsArray);
}
这有一些未处理的边缘情况(OOBExceptions等),但如果我理解您的要求,这样的东西应该有效:
public Animal[] removeDuplicateAnimals(Animal[] animals, int fromIndex, int toIndex) {
int modifiedAnimalsSize = animals.length;
for (int i = fromIndex; i < toIndex; i++) {
for (int j = i+1; j < toIndex; j++) {
int k = modifiedAnimalsSize -1;
if (animals[i].equals(animals[j])) {
animals[j] = animals[k];
animals[k] = null;
modifiedAnimalsSize--;
j--;
}
}
}
// return a new array which is resized
return Arrays.copyOf(animals, modifiedAnimalsSize);
}
对于数组中索引i处的每只动物,在从i+1到toIndex的数组索引中搜索同一只动物;如果存在重复,请在原始数组中的索引i处写入null。这不会调整数组的大小。它只会用null替换重复项。
public Animal[] removeDuplicateAnimals(Animal[] animals, int fromIndex, int toIndex) {
for (int i = fromIndex; i++; i < toIndex) {
for (int j = i+1; j++; j <= toIndex) {
if (animals[i].equals(animals[j])) {
animals[i] == null;
break;
}
}
}
return animals;
}