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 class Solution {
public int searchInsert(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int start=0;
while(A.length>1){
int half=A.length/2-1;
if(A[half]<target && target<A[half+1])
return start+half+1;
if(A[half]<target){
A=Arrays.copyOfRange(A, half+1, A.length);
start+=half+1;
}
else if(A[half]>target){
A=Arrays.copyOfRange(A, 0, half+1);
}
else
return start+half;
}
if(A[0]>=target)
return start;
else
return start+1;
}
}
class Solution {
public:
int searchInsert(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int begin, mid, end;
begin = 0; end = n-1;
while(begin < end)
{
mid = begin + (end-begin)/2;
if(target == A[mid]) return mid;
else if(target < A[mid])
end = mid;
else
begin = mid+1;
}
return target<=A[begin]?begin:begin+1;
}
};
------------------------------------------------------------------------------------------------------------------------------------------
LL's solution:
Binary search (0011型)
public class Solution {
public int searchInsert(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = A.length;
if(len<1)
return -1;
int start = 0, end = len-1,middle;
// using 0011
while(start<end){
middle = start + (int)(end-start)/2;
if(A[middle]>=target)
end = middle;
else
start = middle+1;
}
if(start==len-1 && A[start]<target)
return start+1;
else
return start;
}
}
Note:
最后要比较start是否为尾端,如果是尾端且小于target,需要返回start+1,即insert在末尾。e.g. [1,3,5], 6
Binary search(1100型)
public class Solution {
public int searchInsert(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = A.length;
if(len<1)
return -1;
int start = 0, end = len-1,middle;
// using 1100
while(start<end){
middle = start + (int)(end-start+1)/2;
if(A[middle]<target)
start = middle;
else
end = middle-1;
}
if(start==0 && A[start]>=target)
return 0;
else
return start+1;
}
}
Note:
同理,最后要比较start是不是为始端且大于等于target,是则需返回0,即insert在始端。
------------------------------------------------------------------------------------------------------------------------------------------
关于二分法小结:(针对从小到大sorted且没有duplicate的list)
经常出现的问题:1.死循环 2. off by one
0011型:
断言函数 middle>=target
middle = start + (int)(end-start)/2,对于偶数长度是中间偏前
middle=0,start = middle+1middle=1,end = middle;
1100型:
断言函数 middle<target
middle = start + (int)(end-start+1)/2,对于偶数长度是中间偏后
middle=0,end=middle-1middle=1,start=middle;
conclusion:
1. 永远都是0那一端的指针可以大胆走到middle下一个(以迫使start和end相遇,结束循环),1那一端只能走到middle
2. middle永远都是靠0端
3. 循环条件:start<end
4. 最后注意判断特殊情况,比如首端尾端
详见:漫谈二分查找