Leetcode::Search Insert Position
二分查找法
class Solution {
public:
int searchInsert(int A[], int n, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int start = 0;
int end = n - 1;
while( start <= end )
{
int mid = ( start + end ) / 2;
if( target == A[ mid ] )
return mid;
else if( target > A[ mid ] )
start = mid + 1;
else
end = mid - 1;
}
return max( start, end );
}
};

浙公网安备 33010602011771号