不是有题解吗,你照着看一遍,二分题有模板的
#include<stdio.h>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public :int search(vector<int>& nums, int target) {
int low = 0, high = nums.size() - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
int num = nums[mid];
if (num == target) {
return mid;
}
else if (num > target) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}
};
void main() {
vector<int>nums = { 1,4,5,7,12,34,55 };
int target = 7;
Solution S ;
int a = S.search(nums, target);
cout << a << endl;
}