描述
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 ,现在想把 target 放入数组中,求插入的位置。
分析
其实就是典型的二分查找,题目本身没有什么难度,这里需要注意的是当 target 比数组中所有数都大的情况。
代码
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.back() < target) return nums.size();
int lo = 0, hi = nums.size() - 1;
while (lo < hi) {
int mi = lo + (hi - lo) / 2;
if (nums[mi] == target) return mi;
if (nums[mi] > target) hi = mi;
else lo = mi + 1;
}
return hi;
}
};