描述
给出一个有序的数组和一个目标值,如果数组中存在该目标值,则返回该目标值的下标。如果数组中不存在该目标值,则返回如果将该目标值插入这个数组应该插入的位置的下标
假设数组中没有重复项。
下面给出几个样例:
[10,30,50,60], 50 → 2
[10,30,50,60], 20 → 1
[10,30,50,60], 70 → 4
[10,30,50,60], 0 → 0
示例1
输入:
[10,30,50,60],50
返回值:
2
class Solution {
public:
int searchInsert(int A[], int n, int target) {
//You may assume no duplicates in the array.
//本题考查二分查找
if(n==0)return 0;
int l=0,h=n,m;
while(l<h){
m = l+((h-l)>>1);
if(A[m]>target){
h=m;
}else if(A[m]<target){
l=m+1;
}else{ //找到了
return m;
}
}
//没有找到
if(target<A[0]) return 0;
if(target>A[n-1])return n;
return h;
}
};