261页binaryMaxIndexSmallerThanValue

来源:互联网 发布:python 参数 编辑:程序博客网 时间:2024/05/23 00:24
#include <iostream>#include <vector>using namespace std;template <typename Type>int binaryMaxIndexSmallerThanValue(const vector<Type> &array ,Type keyValue){if(array.size()==0)return -1;int left=0,right=array.size()-1;while(left<right-1){int midIndex=left+(right-left)/2;if(array[midIndex]<keyValue)  left=midIndex;else                          //此等号位置非常重要right=midIndex;}if(array[right]<keyValue)return right;if(array[left]<keyValue)return left;return -1;}int main(){vector<int> sss;for(int i=1;i<100;++i){sss.push_back(49);}int index=binaryMaxIndexSmallerThanValue(sss,50);if(index>=0)   cout<<index<<" "<<sss[index]<<endl;else   cout<<"NULL"<<endl;system("pause");}

0 0
原创粉丝点击