[容易]二分查找

题目来源:http://www.lintcode.com/zh-cn/problem/first-position-of-target/

可以accept的程序如下:

 1 class Solution {
 2 public:
 3     /**
 4      * @param nums: The integer array.
 5      * @param target: Target number to find.
 6      * @return: The first position of target. Position starts from 0. 
 7      */
 8     int binarySearch(vector<int> &array, int target) {
 9         // write your code here
10         vector<int>::iterator p;
11         p=find(array.begin(),array.end(),target);
12         if(p!=array.end())
13             return p-array.begin();
14         else
15             return -1;
16     }
17 };

可以accept的程序2:

 1 class Solution {
 2 public:
 3     /**
 4      * @param nums: The integer array.
 5      * @param target: Target number to find.
 6      * @return: The first position of target. Position starts from 0. 
 7      */
 8     int binarySearch(vector<int> &array, int target) {
 9         // write your code here
10         if(array.size()==0) return -1;
11         int low,high,mid;
12         low=0;//定义最低下标为首位
13         high=array.size()-1;//定义最高下标为末位
14         while(low<high-1)
15         {
16             mid=(low+high)/2;//对查找的序列一分为二
17             if(target<array[mid])
18                 high=mid-1;//缩小查找范围至[low,mid-1]
19             else if(target>array[mid])
20                 low=mid+1;//缩小查找范围至[mid+1,high]
21             else
22                 high=mid;//不断一分为二,直至mid就是查找的内容
23         }
24         if (array[low] == target) {
25             return low;
26         }
27         if (array[high] == target) {
28             return high;
29         }
30         return -1;
31     }
32 };

可以accept的程序3

 1 class Solution {
 2 public:
 3     /**
 4      * @param nums: The integer array.
 5      * @param target: Target number to find.
 6      * @return: The first position of target. Position starts from 0. 
 7      */
 8     int binarySearch(vector<int> &array, int target) {
 9         // write your code here
10         if (array.size() == 0) {
11             return -1;
12         }
13         int start = 0;
14         int end = array.size() - 1;
15         int mid;
16         while (start + 1 < end) {
17             mid = start + (end - start) / 2;
18             if (array[mid] == target) {
19                 end = mid;
20             } else if (array[mid] < target) {
21                 start = mid;
22             } else if (array[mid] > target) {
23                 end = mid;
24             }
25         }
26         if (array[start] == target) {
27             return start;
28         }
29         if (array[end] == target) {
30             return end;
31         }
32         return -1;
33     }
34 };
posted @ 2016-05-01 19:59  Pearl_zju  阅读(122)  评论(0编辑  收藏  举报