标签:
题目描述:
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 }
标签:
原文地址:http://www.cnblogs.com/ljminseu/p/4794829.html