# Search in Rotated Sorted Array II

89人阅读 评论(0)

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
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：65390次
• 积分：1870
• 等级：
• 排名：千里之外
• 原创：125篇
• 转载：6篇
• 译文：0篇
• 评论：4条
评论排行
最新评论