一.题目
Search in Rotated Sorted Array II
Total Accepted: 29366 Total Submissions: 93463My SubmissionsFollow 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.
Show Tags
Have you met this question in a real interview?
Yes
No
二.解题技巧
这道题和Search in Rotated Sorted Array这道题是类似的,只不过这里允许出现重复的数字而已,因此,我仍然采用二分搜索的变种算法,只不过加入了剔除和第一个元素相同的元素的过程。
三.实现代码
class Solution {
public:
int RemoveDuplicatesFromStart(int* A, int n)
{
int NumberOfDuplicates = 0;
int Start = A[0];
for (int Index = 1; Index < n; Index++)
{
if ( Start != A[Index])
{
break;
}
NumberOfDuplicates++;
}
return NumberOfDuplicates;
}
int RemoveDuplicatesFromEnd(int* A, int n)
{
int NumberOfDuplicates = 0;
int Start = A[0];
for (int Index = n - 1; Index > 0; Index--)
{
if (Start != A[Index])
{
break;
}
NumberOfDuplicates++;
}
return NumberOfDuplicates;
}
bool search(int A[], int n, int target)
{
if (n < 1)
{
return false;
}
if (n == 1)
{
if (A[0] == target)
{
return true;
}
return false;
}
if (n == 2)
{
if (A[0] == target)
{
return true;
}
if (A[1] == target)
{
return true;
}
return false;
}
if (A[0] == target)
{
return true;
}
// remove the duplicates
int DuplicatesFromStart = RemoveDuplicatesFromStart(A, n);
if (DuplicatesFromStart == (n - 1))
{
return false;
}
int DuplicatesFromEnd = RemoveDuplicatesFromEnd(A, n);
if (DuplicatesFromEnd == (n - 1))
{
return false;
}
n = n - DuplicatesFromStart - DuplicatesFromEnd;
if (n < 2)
{
return false;
}
A = A + DuplicatesFromStart;
if (A[n / 2] == target)
{
return true;
}
if (A[0] > target)
{
if (A[0] < A[n / 2])
{
return search((A + n / 2), (n - n / 2 ), target);
}
if (A[n / 2] < target)
{
return search((A + n / 2), (n - n / 2), target);
}
return search(A, (n / 2), target);
}
else
{
if (A[0] < A[n / 2])
{
if (A[n / 2] < target)
{
return search((A + n / 2), (n - n / 2), target);
}
return search(A, (n / 2), target);
}
return search(A, (n / 2), target);
}
}
};
四.体会
我的做法是采用变种的二分搜索算法,只不过是加入了剔除和第一个元素相同的元素的过程,加入了这个过程之后,我使用的方法在最差情况下(所有元素都相同的情况)的时间复杂度为O(n)。可以查看一下别人的代码,看看是否有更好的解决方法。
版权所有,欢迎转载,转载请注明出处,谢谢
