describe:
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.
Analysis:
Repeated elements are allowed, then if A[m]>=A[l] in the previous question, then the assumption that [1,m] is an increasing sequence cannot be established, such as [1,3,1,1,1 ].
If A[m]>=A[l] cannot be determined to increase, then split it into two conditions:
(1) If A[m]>A[l], the interval must increase;
(2) If A [m]==A[l] can not be determined, then i++, just look down one step.
code
// LeetCode, Search in Rotated Sorted Array II
// 时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
bool search(const vector<int>& nums, int target) {
int first = 0, 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
//skip duplicate one
first++;
}
return false;
}
};