我有一个排序数组。给定一个键值(不一定在表中),我想找到表中接近该键值的元素。
我考虑过使用二分搜索,但如果键不在表中(不是-1),我需要返回最接近的元素。我应该尝试做什么?
如果没有匹配项,则返回-1
。这是我当前对二分搜索的尝试:
public static long binarySearch (ArrayList<Long> arr, int first, int last, long key)
{
if (first > last) return -1;
int mid = first + (last - first)/2;
if (arr.get(mid) == key)
return mid;
else if (arr.get(mid) > key)
return binarySearch(arr, first, mid - 1, key);
else
return binarySearch(arr, mid + 1, last, key);
}
最佳答案
更改:
如果(第一个 > 最后一个)返回 -1;
到
if (first > last) {
// if either first or last is negative, return the first element.
// if either first or last are greater than arr length, return the last element.
// otherwise, get values in the array for indecies first and last, compare then to
// your key and return the closest.
}
关于java - 查找ArrayList中最接近的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22044413/