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
解题思路:
典型的二分查找应用,注意数组下标为0~n-1,但是可能数字需要插在数组最后第n的位置上。
由于需要找到一个大于等于target数所在的位置,进行插入;所以当nums[mid] > target时,r应该等于mid;因此采用 mid=(l+r)/2,l=mid+1的组合;
对于二分查找有兴趣的同学,可以看另一道Leetcode题目Search for a Range,对二分查找的应用更加全面,在里面,我也写了一些自己学习二分查找总结的心得;
代码:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l = ;
int r = nums.size();
while (l < r) {
int mid = (l + r) / ;
if (nums[mid] > target)
r = mid;
else if (nums[mid] == target)
return mid;
else
l = mid + ;
}
return r;
}
};