Question
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
本题难度medium。使用二分查找法。有两种写法:递归与迭代。
递归
【复杂度】
时间 O(log(N)) 空间 O(1)
【注意】
本题要加上对target超出了array的范围的情况的处理,也就是:
target<nums[l] 与 nums[r]<target
【代码】
public class Solution {
public int searchInsert(int[] nums, int target) {
//require
if(nums==null)
return -1;
int size=nums.length;
if(size<1)
return -1;
//invariant
return helper(0,size-1,nums,target);
}
public int helper(int l,int r,int[] nums,int target){
//bound
if(r-l+1<=2){
if(target==nums[l])return l;
if(target==nums[r])return r;
if(nums[l]<target&&target<nums[r])return l+1;
}
if(target<nums[l])return l;
if(nums[r]<target)return r+1;
int mid=l+(r-l)/2;
if(nums[l]<=target&&target<=nums[mid])
return helper(l,mid,nums,target);
else
return helper(mid+1,r,nums,target);
}
}
迭代
【复杂度】
时间 O(log(N)) 空间 O(1)
【注意】
第11行while(l<=r){
,而不能写成while(l<r){
,因为这样对于nums为1个元素的情况不会进入循环。
【代码】
public class Solution {
public int searchInsert(int[] nums, int target) {
//require
if(nums==null)
return -1;
int size=nums.length;
if(size<1)
return -1;
//invariant
int l=0,r=size-1,mid=-1;
while(l<=r){
//bound
if(r-l+1<=2){
if(target==nums[l])return l;
if(target==nums[r])return r;
if(nums[l]<target&&target<nums[r])return l+1;
}
if(target<nums[l])return l;
if(nums[r]<target)return r+1;
mid=l+(r-l)/2;
if(nums[l]<=target&&target<=nums[mid])
r=mid;
else
l=mid+1;
}
return -1;
}
}