题目
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.
分析
这是一道类似于LeetCode 33 的题目,不同的就是这道题有可能出现数字重复,所以,我们不可能像上题那样找到旋转点,然后两次二分查找;
我们可以根据序列特点,以二分查找思想为基础,对该算法进行一定程序的改进。
AC代码
class Solution {
public:
bool search(vector<int>& nums, int target) {
if (nums.empty())
return false;
//求所给序列的长度
int len = nums.size();
int lhs = 0, rhs = len - 1;
while (lhs <= rhs)
{
//右移一位减半,提升效能
int mid = (lhs + rhs) >> 1;
if (target == nums[mid])
return true;
//若左侧、中间、右侧值相等 则左右同时内移一位
if (nums[lhs] == nums[mid] && nums[mid] == nums[rhs])
{
lhs++;
rhs--;
}//if
else if (nums[lhs] <= nums[mid])
{
if (nums[lhs] <= target && target < nums[mid])
{
rhs = mid - 1;
}
else{
lhs = mid + 1;
}//else
}//elif
else{
if (nums[mid] < target && target <= nums[rhs])
{
lhs = mid + 1;
}//if
else{
rhs = mid - 1;
}//else
}//else
}//while
return false;
}
};