这是一个练习题考试。除了完整的答案外,我不会赞赏任何提示或改进。
搜索问题是给定(A,K),其中A被排序,找到A中的k的等级,即,找出在A中有多少元素小于k。假设A已经是加载到内存中(所以你不计算读A的时间 - 也许是因为你要在A中进行大量的搜索,所以你只需要读一次)。
给出一个算法来解决搜索,并找到解决这个问题的任何算法的下界,假设k只能与A的元素进行比较。
到目前为止我有什么。 由于数组已经排序,我们不知道数组的大小n,因为它没有给出,我们没有适当的约束来使用二进制搜索。所以为了找到关键位置,
first we find bounds and then apply binary search algorithm.
Let low be pointing to 1st element and high pointing to 2nd element of array, Now compare key with high index element,
->if it is greater than high index element then copy high index in low index and double the high index.
->if it is smaller, then apply binary search on high and low indices found.
And since we are using binary search the complexity will be lon(n).
如果有人提示如何继续解决这个问题,有人可以判断这是否正确。谢谢
答案 0 :(得分:2)
private int rank(int lo, int hi, int[] items, int element) {
int mid = 0;
int rankCount = hi;
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
if (element < items[mid]) {
hi = mid - 1;
} else if (element > items[mid]) {
lo = mid + 1;
} else {
return rankCount + 1 - mid;
}
}
int r = hi;
if (r > rankCount) {
r = 1;
} else if (r < 0) {
r = rankCount + 1 + 1;
} else {
r = rankCount + 1 - r;
}
return r;
}
如果对items数组进行排序并且不应有任何重复项,则此方法有效。