题目:
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.
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 4:
Input: [1,3,5,6], 0 Output: 0
代码:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.size() == 0)return 0;
int i = 0, j = nums.size() - 1, mid = -1;
if (target < nums[i])return i;
if (target > nums[j])return j+1;
while (i <= j) {
mid = (i + j) / 2;
if (nums[mid] > target) {
j = mid - 1;
}
else if (nums[mid] < target) {
i = mid + 1;
}
else {
return mid;
}
}
if (nums[i] > target) return i;
if (nums[i] < target)return i + 1;
return 0;
}
};
注:
1、考虑结尾的插入
2、while的时候一定不能遗漏i=j的情况,需要写成while(i<=j)
3、不要出现任何形式的可能没有return 的情况,否则会编译报错
本文深入探讨了二分查找算法的实现,通过一个具体的代码示例,详细解释了如何在一个已排序的数组中查找目标值,如果目标值不存在,则返回其应该插入的位置。文章涵盖了边界条件的处理、循环条件的确立以及返回值的判断,确保算法的正确性和完整性。
525

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



