Leetcode::Search Insert Position
折半查找:
class Solution {
public:
int searchInsert(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( n <= 0 )
{
return 0;
}
int low = 0;
int high = n-1;
while( low <= high )
{
int mid = (low + high)/2;
if(A[mid] == target)
{
return mid;
}
if( target < A[mid] )
{
high = mid - 1;
}
if( target > A[mid])
{
low = mid + 1;
}
}
return low;
}
};
顺序查找:
class Solution {
public:
int searchInsert(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( n == 0 )
{
return 0;
}
int i;
for( i = 0; i < n; i++)
{
if( A[i] >= target )
{
return i;
}
}
return i;
}
};