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
public static int searchInsert(int[] nums, int target) {
if(nums==null||nums.length==0){
return 0;
}
int l=0;
int h=nums.length-1;
int mid;
while(l<=h){
mid=(l+h)/2;
if(target==nums[mid])
return mid;
if(targetmid])
h=mid-1;
if(target>nums[mid])
l=mid+1;
}
return l;
}
这题思路为二分查找。思路就是每次取中间,如果等于目标即返回,否则根据大小关系切去一半。算法复杂度是O(logn),空间复杂度O(1)。当循环结束时,如果没有找到目标元素,那么l一定停在恰好比目标大的index上,r一定停在恰好比目标小的index上。这个可以通过简单的例子来证明。
通过这个二分查找的基础题,再回顾一下二分查找的递归和非递归方式
int BinSearch(int Array[],int key/*要找的值*/)
{
int low=0,high=Array.length-1;
int mid;
while (low<=high)
{
mid = (low+high)/2;
if(key==Array[mid])
return mid;
if(key<Array[mid])
high=mid-1;
if(key>Array[mid])
low=mid+1;
}
return -1;
}
int BinSearch(int Array[],int low,int high,int key/*要找的值*/)
{
if (low<=high)
{
int mid = (low+high)/2;
if(key == Array[mid])
return mid;
else if(key<Array[mid])
return BinSearch(Array,low,mid-1,key);
else if(key>Array[mid])
return BinSearch(Array,mid+1,high,key);
}
else
return -1;
}