从一个数组中查找和目标数最近的或者相等的数

大疆无人机笔试题,二分法求解:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 #include <stdio.h>
 5 using namespace std;
 6 int binarySearchKey(int *arr,int goal,int len)
 7 {
 8     int i;
 9     for(i = 0;i < len;++i)
10     {
11         cout<<arr[i]<<" ";
12     }
13     int targetindex = 0;
14     int left = 0,right = 0;
15     for(right = len - 1; left != right;)
16     {
17         int midIndex = (right + left)/2;
18         int mid = (right - left);
19         int midValue = arr[midIndex];
20         if(goal == midValue)
21         {
22             return midIndex;
23         }
24         if(goal > midValue)
25         {
26             left = midIndex;
27         }
28         else
29         {
30             right = midIndex;
31         }
32         if(mid <= 1)
33         {
34             break;
35         }
36     }
37     int rightnum = arr[right];
38     int leftnum = arr[left];
39     int ret = abs((rightnum - leftnum)/2) > abs(rightnum -goal) ? rightnum : leftnum;
40     return ret;
41 }
42 int main()
43 {
44     int a[8] = {0,1,2,3,5,6,8,9};
45     int k = binarySearchKey(a,4,8);
46     cout<<"k = " << k <<endl;
47 }
View Code

 

posted @ 2015-10-19 08:47  天天AC  阅读(909)  评论(0编辑  收藏  举报