题目一:search-insert-position
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(int A[], int n, int target) {
int low=0,high=n-1;
while(low<=high)
{
int mid=(low+high)/2;
if(A[mid]==target)
return mid;
else if(A[mid]<target)
{
low=mid+1;
}
else
high=mid-1;
}
return low;
}
};
题目二: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.
代码如下:
class Solution {
public:
int search(int A[], int n, int target) {
if(A[0]<A[n-1])
return binary(A,0,n-1,target);
else
{
int pivot=0;
for(int i=0;i<n;i++)
{
if(A[i]>A[i+1])
{
pivot=i;
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)
{
while(low<=high)
{
int mid=(low+high)/2;
if(A[mid]==target)
return mid;
else if(A[mid]<target)
{
low=mid+1;
}
else
high=mid-1;
}
return -1;
}
};
题目三:search-in-rotated-sorted-array ii
Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
代码如下:
class Solution {
public:
bool search(int A[], int n, int target) {
int pivot=0;
for(int i=0;i<n;i++)
{
if(A[i]>A[i+1])
{
pivot=i;
break;
}
}
int left=binary(A,0,pivot,target);
int right=binary(A,pivot+1,n-1,target);
return left||right;
}
bool binary(int A[],int low,int high,int target)
{
while(low<=high)
{
int mid=(low+high)/2;
if(A[mid]==target)
return true;
else if(A[mid]<target)
{
low=mid+1;
}
else
high=mid-1;
}
return false;
}
};
优化之后的代码如下:
class Solution {
public:
bool search(int A[], int n, int target) {
//首先找到两个子序列的分界点,一般情况下分界点的元素值大于之后的元素值(除了所有元素值相同的情况)
//如 4 4 5 5 2 2的分界点是元素5,如2 2 2 2 2的分界点其实就是位置0的元素2
int fuckQQ=0;
for(int i=0;i<n;i++)
{
if(A[i]>A[i+1])//必须是大于
{
fuckQQ=i;
break;
}
}
//二分查找
int low=0,high=fuckQQ;
while(low<=high)
{
int mid=(high-low)/2+low;
if(target>A[mid])
low=mid+1;
else if(target<A[mid])
high=mid-1;
else return true;
if(low>high)
{
low=fuckQQ+1;
high=n-1;
fuckQQ=n;//目的是控制右边的序列仅仅之多进行一次二分查找,若没有这句话则无限循环右侧的子序列
}
}
return false;
}
};