在排序数组 X 中搜索第一个索引 i,使得 X[i] >= a
Search in sorted array X for first index i such that X[i] >= a
我正在努力适应编码成瘾者在这里提出的代码来解决这个问题的这个简单变体。有人有想法吗?
你采用他的算法,返回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();
}
要查找第一个索引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;
}
这是二叉搜索的采用。
#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
相关文章:
- EASTL矢量<向量<int>>连续的
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 求最小素数 x 和最大 m = power_of(x) 的函数,使得 n % m = 0 和 n % x = 0?
- 在数组中查找对,使得 a+b%10 = k
- 分配/访问2d阵列,使得2d子块是连续的
- 找到所有整数 i, j, k >= 0 使得 i + j + k <= d?
- 从安卓NDK15切换到17使得malloc和朋友找不到
- 构造大小为 N 的数组 A 和大小为 1 的数组 A,使得所有 A[i]*A[j] 的总和为最小值和正数。1 <= i < j <= N
- 派生类中的'using Base<T>::func()'使得派生类之外无法访问'func'
- cmakelists-使得找不到标头文件
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 求数组中三元组 (i, j, k) 的数量,使得 A[i] + A[j] = 2 * A[k]
- 如何打印给定i和j的数字数组,使得i的所有元素的总和等于j
- C 字符串比较“祝您好运”&gt;“再见”
- 可能的数组数,使得相邻元素最多有 1 个差异
- (也许是NP-Hard)求一个集合的子集总数,使得每个子集在与其所有元素相乘时的值都大于X
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 一个数组可以划分的最大子数组,使得不同子数组中任意两个元素的 GCD 始终为 1?
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- C 操作员&gt;&gt;与突变器过载