题目:
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 mid, low=0, high=n-1;
while(low<high){
mid=(low+high)/2;
if(A[mid]==target)return mid;
if(A[mid]>target){
high=mid-1;
}else{
low=mid+1;
}
}
return target>A[low]?low+1:low;
}
};
本文介绍了一种使用二分法解决特定类型问题的方法。当给定一个已排序的数组及一个目标值时,该算法能够返回目标值在数组中应插入的位置。文中还提供了具体的实现代码,有助于读者理解算法的工作原理。
494

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



