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
这道题是二分查找的一个升级版,查到就返回下标;查不到就返回在数组里应在的位置.
#include "iostream"
#include "stdio.h"
#include "stdlib.h"
class Solution{
public:
int searchInsert(int A[], int n, int target){
if (n < 0)
return -1;
int left = 0;
int right = n;
while (left >= 0 && left < right && right <= n){
int mid = (left + right)/2;
if (A[mid] > target){
--right;
}
else if (A[mid] < target)
++left;
else
return mid;
}
if (left == 0)
return left;
if (right == n)
return n;
return left;
}
};
int main(int agrc, char** agrv){
int a[] = {1,3,5,6};
int target = atoi(agrv[1]);
Solution s;
printf("find %d\n", s.searchInsert(a, sizeof(a)/sizeof(*a)
, target));
}