算法本身不难,难的是细节,边界情况
【left,right】
int binarySearch(int nums[], int target) {
int left = 0;
int right = nums.length - 1; // 注意
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1; // 注意
else if (nums[mid] > target)
right = mid - 1; // 注意
}
return -1;
}
左闭右开 :【left,right)
int search(int nums[], int target) {
int left = 0,right = nums.size();
while(left<right){
int mid = left+(right-left)/2;
if(nums.at(mid)==target){
return mid;
}else if(nums.at(mid)<target){
left = mid+1;
}else if(nums.at(mid)>target){
right = mid;
}
}
return -1;
}
};
最后给出该题我的代码
#include <bits/stdc++.h>
using namespace std;
bool isTurn(int a[], int n){
for(int i=0;i<n-1;i++){
for(int j=i;j<n;j++){
if(a[i]>a[j]) return false;
}
}
return true;
}
bool isRepeat(int a[], int n){
for(int i=0;i<n-1;i++){
int temp = a[i];
for(int j=i+1;j<n;j++){
if(temp == a[j]) return true;
}
}
return false;
}
int main(){
int n,key;
cin >> n >> key;
int a[10];
for(int i=0;i<n;i++){
cin >> a[i];
}
if(isRepeat(a,n) || !isTurn(a,n)){
cout << "Invalid Value";
return 0;
}
int flag = 0;
int left = 0, right = n-1;
while(left <= right){
int mid = left + (right-left)/2;
printf("[%d,%d][%d]\n",left,right,mid);
if(a[mid] > key) right = mid-1;
else if(a[mid] < key) left = mid+1;
else{
flag = 1;
cout << mid;
break;
}
}
if(!flag) cout << "Not Found";
return 0;
}