二分查找力扣702
左闭右闭方法and左闭右开方法
#include<iostream> #include<vector> using namespace std; vector<int>a; //区间是左闭右闭 int search1(vector<int>& nums,int targer) { int left = 0; int right = nums.size() - 1; while(left <= right) { int middle = left + (right - left)/2; if(nums[middle] < targer) { left = middle + 1; } else if(nums[middle] > targer) { right = middle - 1; } else { return middle; } } return -1; } // 区间是左闭右开 int search2(vector<int>& nums,int targer) { int left = 0; int right = nums.size()-1; while(left < right) { int middle = left + (right - left)/2; if(nums[middle] < targer) { left = middle + 1; } else if (nums[middle] > targer) { right = middle; } else { return middle; } } return -1; } int main() { int n; while(1) { cin >> n; a.push_back(n); if(cin.get()=='\n') { break; } } int tag; cin >> tag; int res; // res = search1(a,tag); res = search2(a,tag); cout << res ; return 0; }