Description
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Follow up
1.This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
2.Would this affect the run-time complexity? How and why?
Solution 1(C++)
class Solution {
public:
bool search(vector<int>& nums, int target) {
int left = 0, right = nums.size()-1, mid;
while(left<=right)
{
mid = (left + right) >> 1;
if(nums[mid] == target) return true;
if( (nums[left] == nums[mid]) && (nums[right] == nums[mid]) ) {++left; --right;}
else if(nums[left] <= nums[mid])
{
if( (nums[left]<=target) && (nums[mid] > target) ) right = mid-1;
else left = mid + 1;
}
else
{
if((nums[mid] < target) && (nums[right] >= target) ) left = mid+1;
else right = mid-1;
}
}
return false;
}
};
后续更新
2018-5-12目前为止遇到的同类型的题目1,2;
2018-5-16更新题目3;
- LeetCode-33. Search in Rotated Sorted Array
- LeetCode-153. Find Minimum in Rotated Sorted Array
- LeetCode-34. Search for a Range
算法分析
关于二分搜索,可以参考:
这一道题是在LeetCode-33. Search in Rotated Sorted Array 的基础之上进一步取消了33题中数列严格递增的条件,由于数列中有可能存在多个连续相同的元素,所以要额外加一句:
if( (nums[left] == nums[mid]) && (nums[right] == nums[mid]) ) {++left; --right;}
程序分析
略。