Lower Bound
This is a problem I came across in Google interview, and I was caught off guard. The interviewer asked me to implement the lower_bound(·) function in STL. Here is the code:
int lower_bound(int *array, int size, int key)
{
int first = 0, middle;
int half, len;
len = size;
while(len > 0) {
half = len >> 1;
middle = first + half;
if(array[middle] < key) {
first = middle + 1;
len = len-half-1;
}
else
len = half;
}
return first;
}
Upper Bound
Similarly we have:
int upper_bound(int *array, int size, int key)
{
int first = 0, len = size-1;
int half, middle;
while(len > 0){
half = len >> 1;
middle = first + half;
if(array[middle] > key)
len = half;
else{
first = middle + 1;
len = len - half - 1;
}
}
return first;
}

本文介绍了在Google面试中遇到的一个问题:如何实现STL中的lower_bound和upper_bound函数,并提供了具体的代码示例。这两个函数分别用于查找不小于指定值的最小元素的位置和不大于指定值的最大元素的位置。
1118

被折叠的 条评论
为什么被折叠?



