题目
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
二分查找
代码:
class Solution {
public:
int searchInsert(int A[], int n, int target) {
int begin=0,end=n-1,mid;
while(begin<=end)
{
mid=(begin+end)/2;
if(A[mid]==target)
return mid;
else if(A[mid]<target)
begin=mid+1;
else
end=mid-1;
}
return begin;
}
};
本文介绍了一种使用二分查找算法解决特定问题的方法。给定一个已排序的数组及目标值,若找到目标则返回其索引;若未找到,则返回目标值按顺序插入数组后的位置索引。通过一个C++类的实例展示了如何实现该算法。
505

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



