For a given sorted array (ascending order) and a number target , find the first index of this number in time O(log n) complexit Y.
If the target number does not exist in the array, return -1 .
Has you met this question in a real interview? YesExample
If the array is [1, 2, 3, 3, 4, 5, 10] , for given target 3 , return 2 .
Two-point Search
Class Solution {public: /** * @param the 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 len = array.size () ; int i = recurse (array,target,0,len); if (i! =-1) { while (array[i-1] = = target) {- I. } return i; } return-1; } int recurse (vector<int> &array, int target,int lo,int hi) { if (lo = = hi) { return-1; } int mid = (lo + hi) >>1; if (Target > Array[mid]) { return recurse (Array,target,mid+1,hi); } else if (Target < Array[mid]) { return recurse (Array,target,lo,mid); } else { return mid;}} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Lintcode Binary Search