【题目描述】
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
二分查找的题目,如果插入的数已经存在,则插在值一样的那个数的位置上。
【代码】
非递归:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n=nums.size()-1;
int low,high,middle;
low=0;
high=n;
while(low<high){
middle=(low+high)/2;
if(target>nums[middle]&&target<nums[high]){
low=middle+1;
continue;
}
if(target<nums[middle]&&target>nums[low]){
high=middle;
continue;
}
if(target<=nums[low]) return low;
if(target==nums[high]) return high;
if(target>nums[high]) return high+1;
if(target==nums[middle]) return middle;
}
if(low==high) return target<=nums[low]?low:low+1;
}
};递归:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.empty()) return 0;
return search(nums,0,nums.size()-1,target);
}
int search(vector<int>& nums,int low,int high,int target){
int middle=(low+high)/2;
if(low==high) return target<=nums[low]?low:low+1;
if(target==nums[middle]) return middle;
if(target<nums[middle]) return search(nums,low,middle,target);
if(target>nums[middle]) return search(nums,middle+1,high,target);
}
};
本文详细解释了如何使用二分查找算法解决搜索插入位置的问题,并提供了非递归和递归两种实现方式的代码示例。适用于对算法理解和实现感兴趣的读者。
301

被折叠的 条评论
为什么被折叠?



