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.
int searchInsert(vector<int>& nums, int target) {
if (nums.size() == 0) return 0;
int low = 0, high = nums.size() - 1, mid;
while (low <= high)
{
mid = (low + high) / 2;
if (nums[mid] < target) low = mid + 1;
else if (nums[mid] > target) high = mid - 1;
else return mid;
}
//此时low>high
return low;
}

本文介绍了一个简单的二分搜索算法实现,用于在一个有序数组中查找特定的目标值。如果找到该值,则返回其下标;如果没有找到,则返回该值应该被插入的位置。
466

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



