二分算法
//
// Created by anska on 2022/3/6.
//
#include <vector>
#include "iostream"
using namespace std;
class Search{
public:
Search(vector<int> &nums,int target){
int left = 0;
int right = nums.size()-1; //闭合区间[a,b]
while(left<right){
int middle = left +((right-left)/2);
if(nums[middle]>target){
right = middle-1; //target在左区间,所以[left,middle-1]
}else if (nums[middle]<target){
left = middle+1; //target在右区间,所以[middle+1,right];
}else{ //找到目标值
std::cout<<middle<<std::endl;
return;
}
}
std::cout<<-1<<std::endl;
return;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
vector<int> nums = {-1,0,3,5,9,12};
int target = 3;
new Search(nums,target);
return 0;
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 ggchzzz@163.com