class Solution {
public:
int getMid(int a, int b)
{
return (a + b) / 2;
}
int aux(int A[], int start, int end, int target)
{
int mid = getMid(start, end);
if (start>end)
{
//if (start == end) // consider the extreme things;
// cout << "start == end" << endl;
//if (start > end)
//{
// cout << start <<" !~! "<< end << endl;
// cout << "start > end" << endl;
//}
return -1;
}
if (A[mid] == target)
return mid;
if (A[mid]<target)
{
start = mid;
aux(A, start+1, end, target);//!!!!!!
}
else
{
end = mid;
aux(A, start, end-1, target);//!!!!!!
}
}
int searchInsert(int A[], int n, int target) {
int k_result = aux(A,0,n-1,target);
if( k_result == -1)
{
int i = 0;
while(A[i]<target && i<=n-1)
{
++i;
}
if(i == 0)
return i;
else
if(i == n)
{
return n;
}
else
{
return i;
}
}
else
{
return k_result;
}
}
};
牛逼解法:
http://fisherlei.blogspot.com/2013/01/leetcode-search-insert-position.html