您的位置:首页 > 其它

Leetcode103: Search in Rotated Sorted Array II

2015-10-17 21:15 375 查看
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.

前两种情况跟上篇博客一样,第三种情况是当中间元素等于首部元素时,此时没法判断哪一部分有序,只能将查找区间左边界加1

class Solution {
public:
bool search(vector<int>& nums, int target) {
int n = nums.size();
if(n==0)    return false;
int l = 0;
int r = n-1;
while(l<=r)
{
int mid = (l+r)/2;
if(nums[mid] == target) return true;
else if(nums[l] < nums[mid])
{
if(nums[l]<=target && target<nums[mid])
r = mid-1;
else
l = mid+1;
}
else if(nums[l] > nums[mid])
{
if(nums[mid]<target && target<=nums[r])
l = mid+1;
else
r = mid-1;
}
else
l++;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: