算法-数组:二分查找
在一个有序(假设升序)无重复元素的数组nums中,寻找元素target,找到了就返回对应的下标,没找到就返回-1。
#include <iostream>
#include <vector>
using namespace std;
//二分查找的前提有两个:有序数组、无重复元素
//“循环不变量规则”:边界要么左闭右闭,要么左闭右开
//方法一:左闭右闭
int method(vector<int>& nums,int target){
int n = nums.size();
int left = 0;
int right = n-1;
while(left<=right){//因为是左闭右闭,所以此区间内有可能存在left=right的情况
int middow = (left+right)/2;
if(target == nums[middow]){
return middow;
}
else if(target < nums[middow]){//在左半边
right = middow-1;
}
else{//在右半边
left = middow+1;
}
}
return -1;
}
int main(){
int n;//数组长度
cin>>n;
vector<int> nums;
int num;
for(int i = 0; i < n; i++){
cin>>num;
nums.push_back(num);
}
int target;
cin>>target;
cout<<"目标值所在下标为:"<<method(nums,target);
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
//方法二:左闭右开
int method(vector<int>& nums,int target){
int n = nums.size();
int left = 0;
int right = n-1;
while(left<right){//因为是左闭右开,所以此区间内不可能存在left=right的情况
int middow = (left+right)/2;
if(target == nums[middow]){
return middow;
}
else if(target < nums[middow]){//在左半边
right = middow;
}
else{//在右半边
left = middow+1;
}
}
return -1;
}
int main(){
int n;//数组长度
cin>>n;
vector<int> nums;
int num;
for(int i = 0; i < n; i++){
cin>>num;
nums.push_back(num);
}
int target;
cin>>target;
cout<<"目标值所在下标为:"<<method(nums,target);
return 0;
}