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
Seen this question in a real interview before?
Yes
搜索插入位置
给定一个排序的数组和一个目标值,如果找到目标值,则返回索引值,如果没有,请按照大小进行插入,并返回插入位置的下标
例如:[1,3,5,6],目标5 有,下标为2
[1,3,5,6] 目标2 没有,找到位置下标为1地方插入
代码:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int start=0,end=nums.size(),mid;//因为要插入,所以位置加1,防止插入
while(start < end)
{
mid=(start+end)/2;
if(nums[imd]>=target)
end=mid;
else
start=mid+1;
}
return start;
}
};

本文介绍了一种在已排序数组中查找目标值或确定其插入位置的算法。通过使用二分查找的方式,该算法能够在O(log n)的时间复杂度内找到目标值的索引或者返回目标值应该被插入的位置。
441

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



