难度: Easy
链接
题目内容
Given a sorted array and a target value, return the index if the target is found. If not, return the index
where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
分析
这道题比较简单,就是二分查找。思路就是每次取中间,如果等于目标即返回,否则根据大小关系切去一半。因此算法复杂度是O(logn),空间复杂度O(1)。
C++实现
int searchInsert(int[] A,int target){
if(A == null || A.length ==0){
return 0;
}
int l=0;
int len = A.length-1;
while(l <= r){
int mid = (l+r)/2;
if( A[mid] == target){
return mid;
}if(A[mid] < target){
l =mid+1;
}
else
r=mid -1;
}
return l;
}