题目描述:
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:
- This is a follow up problem to Search in Rotated Sorted Array, where
numsmay contain duplicates. - Would this affect the run-time complexity? How and why?
旋转数组的搜索,元素可能重复,所以在极端情况有可能存在nums[mid]=nums[end],此时①数组右半段都是nums[mid],即旋转点在数组左半段;②数组左半段都是nums[mid],即旋转点在数组右半段。这种情况下,无法确定往哪一边搜索,只能让end向mid移动,缩小搜索范围,所以最差情况的时间复杂度变成O(n)。
class Solution {
public:
bool search(vector<int>& nums, int target) {
int begin=0;
int end=nums.size()-1;
while(begin<=end)
{
int mid=(begin+end)/2;
if(nums[mid]==target) return true;
else if(nums[mid]<nums[end])
{
if(target>nums[mid]&&target<=nums[end]) begin=mid+1;
else end=mid-1;
}
else if(nums[mid]>nums[end])
{
if(target>=nums[begin]&&target<nums[mid]) end=mid-1;
else begin=mid+1;
}
else if(nums[mid]==nums[end]) end--;
}
return false;
}
};
本文探讨了在一个可能含有重复元素且被旋转过的升序数组中搜索特定目标值的问题。给出了一种解决方案,并讨论了其时间复杂度的变化。通过示例说明了算法的工作原理。
411

被折叠的 条评论
为什么被折叠?



