首页 > 其他 > 详细

Binary Search(Easy,二分搜索)

时间:2015-09-09 16:20:40      阅读:286      评论:0      收藏:0      [点我收藏+]

题目描述:

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1.

 
样例:

If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

挑战:

If the count of numbers is bigger than 2^32, can your code work properly?

code:

 1 int binarySearch(vector<int> &array, int target) {
 2         // write your code here
 3         long long first = 0; //防止数据过大,用long long类型
 4         long long nums = array.size();
 5         long long last = nums-1;
 6         long long mid;
 7         while(first <= last){
 8             mid = first + ((last - first + 1) >> 1);//防止数据过大,用移位
 9             if(array[mid] == target){
10                 if(mid == first || array[mid] > array[mid - 1])
11                     return mid;//相等时,当mid等于first或者mid指向的位置大于前一个位置才能说明是首个
12                 else if(array[mid] == array[mid - 1])//否则继续二分,找到第一个
13                     last = mid -1;
14             }else if(array[mid] > target){
15                 last = mid - 1;
16             }else{
17                 first = mid + 1;
18             }
19         }
20         return -1;
21     }

 

Binary Search(Easy,二分搜索)

原文:http://www.cnblogs.com/ljminseu/p/4794829.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!