1.题目
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
有序数组A和一个数target,如果target在A中,返回下标;如果不在,则返回插入该数组后的下标。
2.分析
二分查找,递归or迭代
3.代码
迭代
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int start = 0;
int end = nums.size() - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
end = mid - 1;
else
start = mid + 1;
}
return start;
}
};
递归
int binaryS(vector<int>& nums, int target,int start, int end) {
if (start > end)
return start;
if (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
return binaryS(nums, target, start, mid - 1);
else
return binaryS(nums, target, mid + 1, end);
}
}
int searchInsert(vector<int>& nums, int target) {
if (nums.empty())
return 0;
return binaryS(nums, target, 0, nums.size() - 1);
}