二分查找LintcodeNo14
14First Position of Target
二分查找的基础题
STL lower_bound实现
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
auto res_it=lower_bound(nums.begin(),nums.end(),target);
auto it=nums.begin();
int i=0;
if(*res_it != target)return -1;
return &(*res_it)-&(nums[0]);
}
};
迭代器和下标可使用 取地址符 进行转换 (原理是vector变量在内存上连续分布)
传统算法实现
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 left = -1;
int right = nums.size();
while(right - left > 1)
{
int mid = (left+right)/2;
if(target<=nums[mid])
{
right = mid;
}else{
left = mid;
}
}
if(nums[right] != target)return -1;
return right;
}
};
需要注意的是
- 区间为左开 (其原因是 整型变量 (2+3)/2=3 )
- 当搜索到=号的时候,拉右边到中间(right = mid)