我的问题是1.不会用二分法直接找到一个局部极大值,只是实现了输入一个值来判断
2.调用函数不知道怎么返回二维数组下标。
#include<iostream>
#include<vector>
using namespace std;
int Find(int target, vector<vector<int> > array);
int main(){
vector<int> v;
vector< vector<int> > test;
int n,temp;
cin >> n;
test.clear();
for(int i=0;i<n;i++){
v.clear();
for(int j=0;j<n;j++){
cin >> temp;
v.push_back(temp);
}
test.push_back(v);
}
int target;
cin >> target;
int a = Find(target,test);
if(a == 0){
cout<<"找不到peak!"<<endl;
}
else{
cout<<a<<endl;
}
return 0;
}
int Find(int target, vector<vector<int> > array) {
if(array.size() == 0 || array[0].size()==0)
return 0;//0表示找不到
int rows = array.size();
int clos = array[0].size();
int left = 0, right = rows-1;
int mid;
while(left <= right){
mid = ( left + right )/2;
if(array[mid][0] <= target){
left = mid+1;
}else{
right = mid-1;
}
}
int rowIndex = mid;
for(int i=rowIndex; i>=0; i--){
left = 0;
right = clos - 1;
while(left <= right){
int mid = (left + right)/2;
if(array[i][mid] == target){
return array[i][mid]; //不会返回下标就返回来查找到的数值
}else if(array[i][mid] > target){
right = mid -1;
}else{
left = mid +1;
}
}
}
return 0; //0表示找不到
}