# 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.

• A[mid]>A[first],则区间一定递增。
• A[mid] == A[first],什么都确定不了，所以first指针前移一位，越过重复元素。

#### C++

class Solution {
public:
bool search(vector<int>& nums, int target) {
int first = 0;
int last = nums.size();
while(first != last)
{
const int mid = first + (last - first) / 2;
if(nums[mid] == target)
return true;
if(nums[first] < nums[mid])
{
if(nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
}
else if(nums[first] > nums[mid])
{
if(nums[mid] < target && target <= nums[last-1])
first = mid + 1;
else
last = mid;
}
else
first++;
}
return false;
}
};

#### Java

public class Solution {
public boolean search(int[] nums, int target) {
int first = 0;
int last = nums.length;
while(first != last)
{
int mid = first + (last - first) / 2;
if(nums[mid] == target)
return true;
if(nums[first] < nums[mid])
{
if(nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
}
else if(nums[first] > nums[mid])
{
if(nums[mid] < target && target <= nums[last-1])
first = mid + 1;
else
last = mid;
}
else
first++;
}
return false;
}
}

#### Python

class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
first = 0
last = len(nums)
while(first != last):
mid = first + (last - first) / 2;
if(nums[mid] == target):
return True
if(nums[mid] > nums[first]):
if(nums[first] <= target and target < nums[mid]):
last = mid
else:
first = mid + 1
elif(nums[mid] < nums[first]):
if(nums[mid] < target and target <= nums[last-1]):
first = mid + 1
else:
last = mid
else:
first += 1
return False

• 本文已收录于以下专栏：

举报原因： 您举报文章：Search in Rotated Sorted Array II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)