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.
这个和前面的一个不一样就在于可能会有重复的数字,那么判断的时候就应该注意了,遇到start<=mid的不一定说明当前的区间[start, mid]就是递增的。这时候就应该++来确认下,代码如下:
// LeetCode, Search in Rotated Sorted Array II
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool search(vector<int>&nums, int target) {
int first = , last = nums.size()-;
while (first <= last) {
const int mid = (first + last) / ;
if (nums[mid] == target)
return true;
if (nums[first] < nums[mid]) {
if (nums[first] <= target && target < nums[mid])
last = mid - ;
else
first = mid + ;
} else if (nums[first] > nums[mid]) {
if (nums[mid] < target && target <= nums[last])
first = mid + ;
else
last = mid;
} else
//skip duplicate one
first++;
}
return false;
}
};