0
我正在尝试使用二进制搜索方法编写已排序字典的删除方法。我的字典是一个位置列表,基于排序的字典。搜索方法如下:删除方法排序字典java
private Entry<Integer, V> binarySearch(int key, int low, int high) {
int mid = (high + low)/2;
if(low > high){
return null;
}
else if(sortedList.get(mid).getKey() == key){
return sortedList.get(mid);
}
else if(sortedList.get(mid).getKey() > key){
return binarySearch(key, low, mid-1);
}
else{
return binarySearch(key, mid+1, high);
}
}
到目前为止我的代码是:
@Override
public Entry<Integer, V> remove(Entry<Integer, V> e)
throws InvalidEntryException {
if(e == null){
throw new InvalidEntryException("");
}
Entry<Integer, V> entry = binarySearch(e.getKey(), 0, size());
if(entry != e){
boolean found = false;
int i = getLocation(entry.getKey());
while(!found && i < size()-1){
entry = binarySearch(e.getKey(), i+1, size());
if(entry == e){
found = true;
sortedList.remove(i);
}
i++;
}
}
else{
sortedList.remove(getLocation(entry.getKey()));
}
if(entry == null){
throw new InvalidEntryException("");
}
else{
return entry;
}
}
任何人都可以对任何输入的所有帮助?我真的不知道如何去做这件事,我已经无法沮丧了。我基本上需要删除,如果条目是参数相同的实例。与字典一样,可能有多个条目具有相同的键,但只有在条目与参数是同一实例时才需要删除。
谢谢你的帮助。
不,我明白。我不想重写equals方法。我被指示使用==运算符而不是更改equals() – ola 2013-02-11 16:42:21