我正在努力调整codaddict proposed here找到的代码来解决问题 这个简单的问题变种。有人有想法吗?
答案 0 :(得分:2)
您采用他的算法,并返回high
而不是-1
。如果X[high]
小于您的目标,请改为使用下一个项目。如果high
等于您的数组大小,则没有这样的索引。
迈克尔·安德森(Michael Anderson)对你所指出的算法的编写方式是正确的,但它很容易适应。
int find_hi (const std::vector<int> &X, int t) {
int low = 0;
int high = X.size() - 1;
while(low <= high) {
int mid = (low + high) / 2;
if(X[mid] == t) return mid;
else if(X[mid] < t)
low = mid + 1;
else
high = mid - 1;
}
if (high < sz && X[high] < t) ++high;
return high;
}
但是,这相当于C ++中的以下内容:
int find_hi (const std::vector<int> &X, int t) {
return std::lower_bound(X.begin(), X.end(), t) - X.begin();
}
答案 1 :(得分:1)
这是binary search的改编。
#include <list>
#include <iostream>
int arr[9]={0,1,2,3,4,5,7,7,8};
/*int * array - where to search
int numberOfElements - the number of elements in array
int targetValue - the value that we are looking for
*/
int find( int * array, int numberOfElements, int targetValue)
{
//we start with searching in the whole array (this is our "scope").
int left = 0;
int right = numberOfElements;
while(left < right)
{
//We take the middle item of our "scope" and compare it with the target value.
int mid = (left + right) / 2;
if( array[ mid ] >= targetValue)//If we did hit
{
//we check is it the first item to match our criteria.
if(array[ mid - 1 ] < targetValue)
{
//If it is, we return the index.
return mid;
}
else
{
//Else, we continue searching to the left.
right = mid;
}
}
//If we didnt hit from the first guess, we continue with our "scope"
//being either the left of the right half of the previous "scope".
else if( array[mid] > targetValue )
right = mid;
else
left = mid;
}
}
int main()
{
std::cout << find(arr, 9, 7);
}
output: 3
答案 2 :(得分:1)
要查找第一个索引i
,其中X[i] >= a
需要修改这样的结束条件,以检查它是否真的是满足条件的第一个索引:
public int findIndex(int[] array, int target) {
int left = 0;
int right = array.length;
while (left < right) {
int mid = (left + right) / 2;
if (array[mid] >= target && (mid == 0 || array[mid - 1] < target)) {
return mid;
} else if (array[mid] > target) {
right = mid;
} else
left = mid;
}
return -1;
}