"title"
Given an ordered (non-descending) array A, which can contain duplicate elements, the smallest I makes a[i] equals target, and returns 1 if it does not exist.
"Analysis"
This is where the target first appears in the array. There might be people here who would like to search directly with the original binary, if there is no direct return-1,
If it exists, then the leftmost position that equals the target value interval is found, so that the worst-case complexity is O (n), and does not fully play the two-point lookup advantage.
Please refer to the implementation code and comments for the specific procedure of this solution.
"Code"
/********************************** Date: 2015-01-05* sjf0115* title: Given an ordered (non-descending) array A, which can contain duplicate elements, the smallest I makes a[i] equals target, does not exist returns -1* blog: **********************************/#include <iostream>using namespace Std;int BinarySearch (int a[],int n,int target) { if (n <= 0) { return-1; } If int start = 0,end = N-1; Two-point find variant while (Start < end) { int mid = (start + end)/2; if (A[mid] < target) { start = mid + 1; } If else{ end = mid; } else }//while //target does not exist// at this time start = end if (A[start]! = target) { return-1; } If else{ return start;} } int main () { int a[] = {2,3,4,4,4,4,4,5,6,7,8}; Cout<<binarysearch (a,11,4) <<endl; return 0;}
[classic face question] given an ordered (non-descending) array A, can contain duplicate elements, the minimum I so that a[i] equals target, does not exist return-1