Binary Search Template
Find first position of sth
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.
/**
* 本代码由九章算法编辑提供。没有版权欢迎转发。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
* - 更多详情请见官方网站:http://www.jiuzhang.com/
*/
#include <vector>
using namespace std;
class Solution {
public:
/**
* @param array source array
* @param target target to search
* @return the first occurrence position of target
*/
int binarySearch(vector<int> &A, int target) {
if (A.size() == 0) {
return -1;
}
int start = 0;
int end = A.size() - 1;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A[mid] == target) {
end = mid;
} else if (A[mid] < target) {
start = mid;
} else if (A[mid] > target) {
end = mid;
}
}
if (A[start] == target) {
return start;
}
if (A[end] == target) {
return end;
}
return -1;
}
};