题目描述
给出一个有序的数组和一个目标值,如果数组中存在该目标值,则返回该目标值的下标。如果数组中不存在该目标值,则返回如果将该目标值插入这个数组应该插入的位置的下标
假设数组中没有重复项。
下面给出几个样例:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
tips: 没有仔细看样例啊,最后一种咋没考虑到呢
class Solution {
public:
int searchInsert(int* A, int n, int target)
{
if(A[0] >= target)
return 0;
for(int i = 1; i < n; i++)
{
if(A[i] == target)
return i;
if(A[i-1] < target && A[i] > target)
return i;
}
}
};