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.

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

1.方法1:搜索左闭右闭区间

注意求中间值尽量避免使用(l+r)/2,因为l+r可能会溢出;
所以尽量用l+(r-l)/2这样就中间值;

class Solution {
public:
/**
* @param nums: The integer array.
* @param target: Target number to find.
* @return: The first position of target. Position starts from 0.
*/
int binarySearch(vector<int> &array, int target) {
// write your code here
int l=0,r=array.size()-1;
while(l<=r){
int mid=l+(r-l)/2;
if(target==array[mid]){
if(mid==0){
return mid;
}else if(array[mid]!=array[mid-1]){
return mid;
}else{
r=mid-1;
}
}else if(target<array[mid]){
r=mid-1;
}else{
l=mid+1;
}
}

return -1;
}
};

2.方法2:搜索左闭右开空间

class Solution {
public:
/**
* @param nums: The integer array.
* @param target: Target number to find.
* @return: The first position of target. Position starts from 0.
*/
int binarySearch(vector<int> &array, int target) {
// write your code here

int l=0,r=array.size();//
while(l<r){//
int mid=l+(r-l)/2;
if(target<=array[mid]){
r=mid;//
}else{
l=mid+1;
}
}

if(array[l]==target){
return l;
}

return -1;
}
};

代码略简洁些;
注意跟几点不同:

1.r=array.size();
2.while(l< r)
3.r=mid;

如果target存在l是是其左边界索引,否则是其应该插入位置的索引;

左闭右开空间搜索区间是[x,y),返回值的候选区间却是[x,y] (因为循环条件是l< r)

详细见《算法竞赛入门》P229