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
思路:二分法(寻找第一个比target大或相等的元素)
代码:
int searchInsert(int A[], int n, int target) {
int p=0;
int q=n-1;
int mid=0;
while(p<=q)
{
mid=(p+q)/2;
if(target <= A[mid])
{
if(mid>0 && target>A[mid-1])
{
return mid;
}
else if(mid == 0)
{
return mid;
}
else
{
q=mid-1;
}
}
else
{
if(mid+1<n && target<=A[mid+1])
{
return mid+1;
}
else if(mid+1 == n)
{
return mid+1;
}
else
{
p=mid+1;
}
}
}
}
本文介绍了一种在已排序数组中查找目标值插入位置的方法。使用二分查找法找到目标值应该插入的位置,确保数组仍然有序。适用于无重复元素的情况,并提供了具体的实现代码。
981

被折叠的 条评论
为什么被折叠?



