题目一:search-insert-position(注意:返回的是low)
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
代码如下:(注意:返回的是low)
int searchInsert(int A[], int n, int target) {
int low=0,high=n-1;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(A[mid]<target)
low=mid+1;
else if(A[mid]>target)
high=mid-1;
else
return mid;
}
return low;
}
题目2:search-for-a-range(注意:左边界返回的是low,右边界返回的是high)
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return[-1, -1].
For example,
Given[5, 7, 7, 8, 8, 10]and target value 8,
return[3, 4].
代码如下:(注意:左边界返回的是low,右边界返回的时high)
vector<int> searchRange(int A[], int n, int target) {
vector<int> res;
int low=0,high=n-1;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(A[mid]>=target)//left
high=mid-1;
else
low=mid+1;
}
if(A[low]==target)
res.push_back(low);//low是左边界
else
res.push_back(-1);
low=0,high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(A[mid]>target)
high=mid-1;
else
low=mid+1;
}
if(A[high]==target)
res.push_back(high);//high是右边界
else
res.push_back(-1);
return res;
}
题目三:search-in-rotated-sorted-array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7might become4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
代码如下:
int search(int A[], int n, int target) {
if(A[0]<A[n-1])
return binary(A,0,n-1,target);
int pivot=0;//
for(int i=1;i<n;i++)
{
if(A[pivot]<A[i])
pivot=i;
else
break;
}
int left=binary(A,0,pivot,target);
int right=binary(A,pivot+1,n-1,target);
if(left!=-1)
return left;
else if(right!=-1)
return right;
else
return -1;
}
int binary(int A[], int low, int high,int target)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(A[mid]<target)
low=mid+1;
else if(A[mid]>target)
high=mid-1;
else
return mid;
}
return -1;
}