1.题目
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
还是查找,如果找不到,返回应该插入的位置。
2.思路
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int mid;
int start = 0,end = nums.size()-1;
while(start <= end)
{
mid = start + (end - start)/2;
if(nums[mid] == target)
{
return mid;
}
else if(nums[mid] > target)
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
if(end < 0)
return 0;
else if(end == nums.size()-1)
return nums.size();
else
return start;
}
};
本文介绍了一个高效的搜索算法,用于在一个已排序的数组中查找特定目标值的插入位置,确保数组保持有序。通过逐步逼近的方法,该算法不仅能够判断目标值是否存在,还能快速确定其在数组中的正确位置,适用于多种应用场景。
434

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



