二分查找
求帮助 #include <stdio.h>int find(int d[] , int n , int k)
{
int i , r , left , mid , right ;
for(r = -1 , left = 0 , right = n - 1 ; left <= right ;) {
mid = left + (right - left) / 2 ;
if(d == k) {
r = mid ;
break ;
} else {
if(k > d) left = mid + 1 ;
else right = mid - 1 ;
}
}
return r ;
}
int main(void)
{
int a = {0} , i , k , n , m ;
scanf("%d" , & n) ;
for(i = 0 ; i < n ; i ++) scanf("%d" , & a) ;
scanf("%d" , & m) ;
if((k = find(a , n , m)) >= 0) printf("%d\n" , k) ;
else printf("null\n") ;
}
编译运行实况:
D:\\C>g++ -o x x.c
D:\\C>x
15
1 4 9 13 21 34 55 89 144 233 377 570 671 703 812
34
5
D:\\C> 本帖最后由 柿子饼同学 于 2022-11-16 19:53 编辑
没有重复的吧
#include <bits/stdc++.h>
using namespace std;
int arr;// 1314
int n, target;
int ans;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for(int i = 0; i < n; i++) cin >> arr;
cin >> target;
int l = 0, r = n-1, mid;
while(l <= r){
mid = (l + r) / 2;
if(arr > target) r = mid - 1;
else l = mid + 1, ans = mid;
}
if(arr == target) cout << ans ;
else cout << "null";
return 0;
}
页:
[1]