lintcode 14 二分查找
c++
class Solution {
public:
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
int binarySearch(vector<int> &nums, int target) {
// write your code here
int low=0;
int high=nums.size()-1;
while(high-low>1){
if(nums[low+(high-low)/2] > target){
high = low+(high-low)/2;
}
else if(nums[low+(high-low)/2]==target){
break;
}
else{
low = low+(high-low)/2 + 1;
}
}
int mid = low+(high-low)/2;
if(nums[mid]==target){
while(nums[mid-1]==target){
mid--;
}
return mid;
}
else{
return -1;
}
}
};