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
- Difficulty: Medium
时间复杂度O(logn)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low=0,high=nums.size();
if(high==0) return 0;
high=high-1;
while(low<=high)
{
int mid=(low+high)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<target) low=mid+1;
else high=mid-1;
}
return low;
}
};
本文介绍了一种在已排序数组中查找目标值的二分查找算法,并提供了C++实现代码。该算法能在未找到目标值时返回其应当插入的位置,确保了数组的有序性。文章通过几个实例展示了算法的应用场景。
445

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



