Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:Input: nums = [1,3,5,6], target = 7
Output: 4class Solution { public: int searchInsert(vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] >= target) { right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } } return left; } };
核心思路:将问题转换成左侧查找的二分查找法(将等号并入大于的部分)
程序细节:
1.return的left 因为 最后一次循环时left = right = mid,如果nums[mid] < target 时 返回的应该是mid+1的下标,而当nums[mid] >= target 返回的就是mid的 , 因此应该使用left
算法详解
二分查找法的细节:
1.考虑边界值
边界值分为跳出循环的条件边界值和查找时并入的边界值(例题展示的属于左侧查找的方法)
int left = 0, right = size; //关键在于 right = size 还是 size-1
while(left < right) //相当于[left,right) , 如果为 size - 1 就是 [left,right]
{
int mid = (left + right) / 2;
if (a[mid] < target)
{
left = mid + 1; //利用区间理论,左边都闭说明应该再加一
}
if (a[mid] > target)
{
right = mid; //还是利用区间理论,右边为开开区间不能为 mid-1 防止漏掉mid-1这个数
}
}
跳出循环边界可以利用开闭区间的理论。
2.算法思想
本质就是二分法的逼近方法,适用于排好序的插入和查找,对于这个问题的实现利用双指针,同时中间元素的索引 = (左边索引 + 右边索引)/ 2;
在这里 /2 的操作保证奇数时找到中间数的索引,偶数时找到中间两数中左边的数再比较。