Difficulty:medium
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
这道题目是二分搜索的应用,相比较与简单的二分搜索,这个题目要求在找到target时返回index,并且如果没有找到的时候要返回按照大小顺序需要插入元素的位置的index.
那么首先进行一遍二分搜索,如果在二分搜索的过程中找到了matrix[mid]=target,这时直接返回mid作为index。
其次考虑,如果没有找到target,那么在跳出while(left<=right)循环时,由于在循环内部每一次都是控制left=mid+1,right=mid-1,当left+1=right进入循环时,那么mid=left,这时通过判断,改变后left=right,再次进行循环,这时,target!=matrix[mid]的情况下,要么是使left+1,要么是right-1,经过判断都是使left=right+1。
当循环结束,如果在上一步中是由于matrix[mid]<target引起的left+1,那么说明需要返回mid+1位置的index,如果是matrix[mid]>target引起的right-1,这时left的值没有改变,需要返回mid的值就是要插入的值。但是无论哪种情况,都保证了返回的值都恰好等于left的值,所以最后直接返回left即可。
代码如下:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n=nums.size();
int left=0;
int right=n-1;
int mid;
while(left<=right)
{
int mid=(left+right)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<target) left=mid+1;
else right=mid-1;
}
return left;
}
};